pythonpython-3.x

Dictionary key name from combination of string and variable value


Basically, I am trying to append values from a list as key-value pairs to a new dictionary. I want the key names in a specific format and order.

#!/usr/bin/env python3
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for val in range(len(ipv4_list)):
    ipv4_dic[i] = ipv4_list[val]
    i+=1

print(ipv4_dic)

Current output:

{1: '192.168.1.2', 2: '192.168.1.3', 3: '192.168.1.4'}

The above is good but I want to change key names to something like IP1, IP2, etc.

How do I make that in the line ipv4_dic[i] = ipv4_list[key]

I tried something like ipv4_dic["IP"+i] but does not work.

    ipv4_dic["IP"+i] = ipv4_list[val]
TypeError: can only concatenate str (not "int") to str

The expected dictionary output as follows:

{IP1: '192.168.1.2', IP2: '192.168.1.3', IP3: '192.168.1.4'}

Solution

  • Use a dictionary comprehension with enumerate starting a 1:

    ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
    ipv4_dic  = {f'IP{n}':ip for n,ip in enumerate(ipv4_list,1)}
    
    print(ipv4_dic)
    {'IP1': '192.168.1.2', 'IP2': '192.168.1.3', 'IP3': '192.168.1.4'}