Python Variables as Keys to Dict

Python variables as keys to dict

for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]

Convert dictionary entries into variables

This was what I was looking for:

>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
exec(key + '=val')

Use variable as key name in python dictionary

No, there isn't. Also it would be unlikely that such syntax would ever emerge, as the construct

{name}

has been reserved for set literals.

The other alternative you have is to use the dict constructor:

d = dict(name=name)

P.S. since dict is a name that's been defined in the builtins module, please do not name your variables as dict.

Python Retrieve value from dict using variable as key

Store the three keys as three different variables rather than as a string:

key_one = 'beta'
key_two = 'mid'
key_three = 'message'

v = test[key_one][key_two][key_three]

If you already have the keys in the string format you describe, then do some string splitting to produce three variables like the above. You don't want to eval the code as it creates a security risk.

Dictionary key name from combination of string and variable value

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


Related Topics



Leave a reply



Submit