Python variables to dict

Geomario
2 min readOct 15, 2020

--

Proficiency in Python means transform Python variables to dict. When working with data and Python programming language, one of the best things that can happen is to automate a process that saves you time. For real! Tons of data can give enormous headaches.

We have been asked, several times, how to create a dictionary from variables in Python. It will help if you implement the function eval() to create keys. Let me show you, lets code together!

#Code block 1.0#Empty dict
mario_dict = {} #(1)
#Variables #(2)
name = "Mario"
age = 35
auto = "Ford"

In the code block 1.0, first, we have created the empty dict (1), where all the information will be placed. Secondly, we have created the variables that we want to place inside that dict (2). We need to apply the function eval() into a for-loop to iterate and return a dict. Let's stop talking and write the code.

#Code Blocl 2.0
#For-loop creation
for information in ["name", "age", "auto"]: #(1)
mario_dict[information] = eval(information) #(2)
print (mario_dict)

In the second code block, firstly, we loop over the list with the names of the variables (1). The variable name is placed inside the dict, which will 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" : "Mario" , "age" : 35 , "auto" : "Ford"}

That’s it, That simple! And the result you can see it the code block 3.0. If you have further questions about a dictionary, give it a try to my video! And please give me a clap!

What is a Dictionary? FreeDataScientist Youtube channel

Seriously, leave a comment!

Thanks.

Happy coding!

--

--

Geomario
Geomario

Written by Geomario

👨‍💻 Software & Data Developer | Software Research Engineer | MLE

Responses (1)