There are two dictionaries
dic_01 = {"name":"aaa","age":29}
dic_02 = {"name":"bbb","age":19}
I want to make a new dictionary like this
dic_03 = {"aaa": 29, "bbb": 19}
How can I do that?
I tried to solve the problem in this way
import pandas as pd
dic_01 = {"name":"aaa","age":29}
dic_02 = {"name":"bbb","age":19}
df = pd.DataFrame([dic_01,dic_02])
dic_03 = {}
for i in range(len(df.index)):
dic_03[df.loc[i,"name"]] = df.loc[i,"age"]
print(dic_03)
Because I have more than two dictionaries to merge into one dictionary, I want to know the better way to solve the question
CodePudding user response:
# Add key to dic 3
dic_03[dic_01["name"]] = dic_01["age"]
dic_03[dic_02["name"]] = dic_02["age"]
For more than one dictionary. Add all to a list.
dic_01 = {"name":"aaa","age":29}
dic_02 = {"name":"bbb","age":19}
dics = [dic_01,dic_02]
dic_3 = {}
for dic in dics:
dic_3[dic["name"]] = dic["age"]
print(dic_3)
Does this answer your question?
CodePudding user response:
Does it solve your problem?
dict1 = {"name": "aaa",
"age": 29
}
dict2 = {
"name": "bbb",
"age": 19
}
dict3 = {
dict1["name"]: dict1["age"],
dict2["name"]: dict2["age"]
}