Home > database >  Dictionary key name from combination of string and variable value
Dictionary key name from combination of string and variable value

Time:02-13

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'}

CodePudding user response:

It does not work because you are trying to concatenate a string with an integer, which is not allowed in Python.

In order to have your code working with the minimum possible amendments is to transform the integer i to a string, via the str() function, i.e. replacing in your code

ipv4_dic["IP" i] = ipv4_list[val]

with

ipv4_dic["IP" str(i)] = ipv4_list[val]

However, you can use dict comprehension, i.e. you loop each position of the ipv4_dic you're about to create, placing there a key built from each element of your ipv4_list, in a single line of code.

ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {f"IP{i 1}": ipv4_list[i] for i in range(len(ipv4_list))}

Explanation: for each i in the range from 0 to len(ipv4_list) we are building the single dictionary key through an f-string, concatenating the string "IP" to the value i 1 (the range starts at 0, but you want your first dict element to be "IP1", that's why i 1). Then, we set the value for this key as ipv4_list[i], which are the single elements contained in your starting list.

The basic usage is

l = ['A', 'B', 'C']

d = {i : l[i] for i in range(len(l))}

which is pretty similar to your case, without the refinements in the keys creation, since you're incrementing the index (i.e. i) and concatenating it to a string.

CodePudding user response:

ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dict= {}

# enumerate will give you the index and value of the iterator
# f-string can compute the value inside the {} and format it like a string

for index,value in enumerate(ipv4_list):
    ipv4_dict[f"IP{index 1}"] = value
# or 
ipv4_dict_1 = {f"IP{index 1}": value for index,value in enumerate(ipv4_list)}

# out:
print(ipv4_dict)
# {'IP1': '192.168.1.2', 'IP2': '192.168.1.3', 'IP3': '192.168.1.4'}
print(ipv4_dict_1)
# {'IP1': '192.168.1.2', 'IP2': '192.168.1.3', 'IP3': '192.168.1.4'}

CodePudding user response:

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'}

CodePudding user response:

I almost didn’t post this because Georgio almost had what I would have written: use a dictionary comprehension based on a for loop. Andd tell you about the str and int concatenation.

The only thing missing was using enumerate to get the list indices. Full of goodness, is enumerate. It returns the elements from an iterable as a list of pairs (tuples): first item is the zero-based index, second is what the for loop (well actually the iterable at that index) would normally return.

Then those pairs get assigned to i,v via tuple unpacking.

di = { f"IP{i 1}":v for i,v in enumerate( [" 192.168.1.2", "192.168.1.3", "192.168.1.4"])}
print(di)

See https://docs.python.org/3/library/functions.html#enumerate

CodePudding user response:

Dictionaries work like this:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

Try this:

ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for key in range(len(ipv4_list)):
    auxStr = "IP"   str(i)  #convert i to string, and merging IP
     ipv4_dic[auxStr] = ipv4_list[key]
    i =1

print(ipv4_dic)

This should do it! Happy coding!!!

  • Related