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
Finding the Consecutive Zeros in a Numpy Array
Installing Scipy in Python 3.5 on 32-Bit Windows 7 MAChine
Saving Upload in Flask Only Saves to Project Root
Oserror: [Winerror 193] %1 Is Not a Valid Win32 Application
Web Scraping Program Cannot Find Element Which I Can See in the Browser
Working with Tiffs (Import, Export) in Python Using Numpy
Comparing Two .Txt Files Using Difflib in Python
Generate a List of Datetimes Between an Interval
Python Regular Expression Re.Match, Why This Code Does Not Work
Get Timezone from City in Python/Django
Types That Define '_Eq_' Are Unhashable
Appending Item to Lists Within a List Comprehension
List Comprehension and Lambdas in Python
Python: Changing Methods and Attributes at Runtime
Django Query That Get Most Recent Objects from Different Categories
Python Pandas: Group Datetime Column into Hour and Minute Aggregations