Use Variable as Key Name in Python Dictionary

Python variables as keys to dict

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

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


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.

Dictionary key name from combination of string and variable value

Use a dictionary comprehension with enumerate starting a 1:

ipv4_list = ["", "", ""]
ipv4_dic = {f'IP{n}':ip for n,ip in enumerate(ipv4_list,1)}

{'IP1': '', 'IP2': '', 'IP3': ''}

Use variable name as key in dictionary comprehension

Having variables like array1, array2 ... is wrong from the start. Let's suppose that the names are significant names instead.

Then we could use variable names to start with, and look them up in the various variable dictionaries. For instance like this:

import numpy as np

# Make up some data
array1 = np.random.randint(255, size=(4, 4))
array2 = np.random.randint(255, size=(4, 4))
array3 = np.random.randint(255, size=(4, 4))
array4 = np.random.randint(255, size=(4, 4))

# Generate a dict with variable name key and median value
d = {x:np.median(locals().get(x,globals().get(x))) for x in ["array1", "array2", "array3", "array4"]}

>>> d
{'array1': 156.5, 'array2': 76.0, 'array3': 100.0, 'array4': 85.0}

locals().get(x,globals().get(x)) is one way of trying to fetch a variable named x first in locals then in globals. It will overlook nonlocals (but can be done, it's just an even more complex expression).

If it's possible, I'd advise to store the variables in a dictionary from the start, then getting the result is trivial:

datadict = {}
datadict["array1"] = np.random.randint(255, size=(4, 4))
datadict["array2"] = np.random.randint(255, size=(4, 4))
datadict["array3"] = np.random.randint(255, size=(4, 4))
datadict["array4"] = np.random.randint(255, size=(4, 4))

# Generate a dict with variable name key and median value
d = {k:np.median(v) for k,v in datadict.items()}

Turn the dictionary keys into variable names with same values in Python from .mat Matlab files using

In python, method parameters can be passed as dictionnaries with the ** magic:

def my_func(key=None):
print key
#do the real stuff

temp = {'key':array([1,2])}


>>> array([1,2])

How to use a variable as dictionary key using f-string in python?

# Following part is working!!!
print(f'Youve selected {languages[option]}')

Related Topics

Leave a reply