for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]
Answer from dr jimbob on Stack Overflow
Discussions

Turn the dictionary keys into variable names with same values in Python from .mat Matlab files using scipy.io.loadmat - Stack Overflow
I know how to grab the keys with ... in temp.keys() to be variable names instead of strings. I hope this makes sense but this is probably really easy I just can't think how to do it. ... I am collaborating with someone that uses Matlab. They send me files that when loaded with loadmat is in a dictionary ... More on stackoverflow.com
🌐 stackoverflow.com
How to Convert dictionary into local variables inside the function?
I have the dictionary which passing through function which has to convert into local variables where i can use those variables for further operations. That dictionary will be dynamic… def dictlocalconverter(hash): … More on discuss.python.org
🌐 discuss.python.org
0
0
June 10, 2022
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)? - Stack Overflow
I have a list of variable names, like this: ['foo', 'bar', 'baz'] (I originally asked how I convert a list of variables. See Greg Hewgill's answer below.) How do I convert this to a dictionary w... More on stackoverflow.com
🌐 stackoverflow.com
python - Dictionary key name from variable - Stack Overflow
I am trying to create a nested dictionary, whereby the key to each nested dictionary is named from the value from a variable. My end result should look something like this: data_dict = { 'jan... More on stackoverflow.com
🌐 stackoverflow.com
February 25, 2018
🌐
Reddit
reddit.com › r/learnpython › how to create a dictionary where the keys have the same name as variable they are assigned?
r/learnpython on Reddit: How to create a dictionary where the keys have the same name as variable they are assigned?
December 1, 2022 -

Not sure if the title is very clear, let me explain alil.

In javascript, you can create an object like so:

field1 = "aaa"
field2 = "bbb"

testObj = {
   field1,
   field2
}

>>> testObj 
>>> { field1: "aaa", field2: "bbb" }

Is there a way to do this in python, where the variable name become the key's name, and the variable value becomes the key-value pair's value? My current use case btw is I have a function that takes 4 arguments, which are used to create a dict, like so.

def foo(arg1, arg2, arg3, arg4):
    dict1 = {
       "arg1" : arg1,
       "arg2" : arg2,
       "arg3" : arg3, 
       "arg4" : arg4
    }
    ...

I would like to use *args and make this function flexible, but im not sure how to create the dictionary using this method. Thanks in advance

🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-dict.html
Python Dict
'dict' is the name of the Python dict type, so we'll use just 'd' as a generic variable name. >>> d = {} # Create empty dict >>> d['ca'] = 'California' # 1. Set key/value pairs into dict >>> d['ok'] = 'Oklahoma' >>> d['nj'] = 'New Jersey' >>> d['tx'] = 'Texas' >>> val = d['nj'] # 2.
🌐
Python Forum
python-forum.io › thread-26290.html
variable as dictionary name?
April 27, 2020 - Hi I am attempting to create 10 dictionaries without having to code them explicitly. The names of the dictionaries will be: X0, X1, X2, X3 .... X9 for x in range(11): a = str(x) dictionary_name = ('X'
🌐
LinuxQuestions.org
linuxquestions.org › questions › programming-9 › python-create-variables-from-dictionary-keys-859776
[SOLVED] Python: Create variables from dictionary keys
January 31, 2011 - Hi all, I have a situation where i need to turn a dictionary entry into a variable. I think i'm close, but am getting a syntax error (quoted at bottom)
🌐
Medium
geomario1984.medium.com › python-variables-to-dict-3de3d765efb1
Python variables to dict. Proficiency in Python means transform… | by Geomario | Medium
October 20, 2020 - In the second code block, firstly, ... transform them into keys, and the eval() function will extract the value of the variable from the key and create the correspondent key-value dict item (2). #Code block 3.0 #Output {"name" ...
Top answer
1 of 7
12

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])}

my_func(**temp)

>>> array([1,2])
2 of 7
5

The best thing to do is to use temp['key']. To answer the question, however, you could use the exec function. The benefits of doing it this way is that you can do this don't have to hard code any variable names or confine yourself to work inside a function.

from numpy import array,matrix

temp = {'key':array([1,2]),'b': 4.3,'c': 'foo','d':matrix([2,2])}

for k in temp:
    exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = repr(temp[k])))

>>> key
array([1, 2])
>>> b
4.3
>>> c
'foo'
>>> d
matrix([[2, 2]])

NOTE : This will only work if you have imported the specific function from the modules. If you don't want to do this because of code practice or the sheer volume of function that you would need to import, you could write a function to concatenate the module name in front of the entry. Output is the same as the previous example.

import numpy as np,numpy

temp = {'key':np.array([1,2]),'b': 4.3,'c': 'foo','d':np.matrix([2,2])}

def exec_str(key,mydict):
    s = str(type(mydict[key]))
    if '.' in s:
        start = s.index("'") + 1
        end = s.index(".") + 1
        v = s[start:end:] + repr(mydict[key])
    else:
        v = repr(mydict[key])     
    return v

for k in temp:
    exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = exec_str(k,temp)))

While this isn't the best code practice, It works well for all of the examples I tested.

Find elsewhere
🌐
Python.org
discuss.python.org › python help
How to Convert dictionary into local variables inside the function? - Python Help - Discussions on Python.org
June 10, 2022 - I have the dictionary which passing through function which has to convert into local variables where i can use those variables for further operations. That dictionary will be dynamic… def dictlocalconverter(hash): for k, v in hash.items(): locals()[k] = v return d dictn = {"a":10,"b":11,"d":"25"} dictlocalconverter(dictn)
🌐
Bobby Hadz
bobbyhadz.com › blog › python-assign-dictionary-value-to-variable
Assign a dictionary Key or Value to variable in Python | bobbyhadz
Copied!my_dict = { 'first_name': ... 'bobbyhadz.com')]) print(my_dict.items()) On each iteration, we use the exec() function to assign the current key-value pair to a variable....
🌐
Quora
quora.com › Is-there-a-way-to-make-the-key-value-pairs-of-a-dictionary-into-variables-in-Python
Is there a way to make the key value pairs of a dictionary into variables in Python? - Quora
Structural pattern matching (Python 3.10+): match d: case {'name': name, 'age': age}: ... ... Prefer explicit assignment or contained objects (SimpleNamespace, dataclass, AttrDict). Avoid injecting into globals() when keys are untrusted or overlap with important names. Validate keys and types before creating variables or attributes. For configuration, prefer dataclasses or typed models (pydantic) for clarity and validation. ... SimpleNamespace: from types import SimpleNamespace config = SimpleNamespace(**{'host':'localhost','port':8000}) print(config.host) # localhost
🌐
Codecademy
codecademy.com › forum_questions › 5146a646f998fa03cb002f93
Is there any way to set name a variable (dictionary) with an item from a list? | Codecademy
Repeating the dictionary setup for three students is cool–but how many classes have three students? students = [“Lloyd”, “Alice”, “Tyler”] breakdown = [“name”, “homework”, “quizzes”, “tests”] for student in students: —-students[student] = {} #Is there any way to write this line so it will work? —-for area in breakdown: ——–student.update({area:””} ——–if area == “name”: ————student.update({“name”:student})
🌐
Quora
quora.com › How-do-I-add-an-entry-into-a-Python-dictionary-when-both-my-key-and-value-are-variables
How to add an entry into a Python dictionary when both my key and value are variables - Quora
In this example, on line five, we’ve added they value “any value” to the dictionary, mydict, under the key “anything.” Obiously this is being done through the variables key and value. This pattern is far more common in Python than using literals: mydict[‘anything’]=‘any value’
🌐
Delft Stack
delftstack.com › home › howto › python › python dynamic variable name
Python Dynamic Variable Name | Delft Stack
December 14, 2023 - In the provided code, variable_name is assigned the value dynamic_var, and value is assigned the string Hello. We then create a dictionary named dynamic_variables using the key-value pair {variable_name: value}.
🌐
Python.org
discuss.python.org › python help
Is there a way to convert a variable name 'this' to this? - Python Help - Discussions on Python.org
October 3, 2023 - I have variables a, b, c, e from a python program. I want to construct a dictionary like this d = {'a': a, 'b': b, 'c': c, 'e':e} Is there a quicker way to construct such a dictionary given [a, b, c, e] or ['a', 'b', 'c', 'e'] Of course, in the real context, the variable names are longer, and ...