how can I let first value to key an second value to value in the new dictionary?


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"]

Because I have more than two dictionaries to merge into one dictionary, I want to know the better way to solve the question

Asked By: tientoen



# 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"]


Does this answer your question?

Answered By: Sifat

Does it solve your problem?

dict1 = {"name": "aaa",
    "age": 29
dict2 = {
    "name": "bbb",
    "age": 19
dict3 = {
    dict1["name"]: dict1["age"],
    dict2["name"]: dict2["age"]
Answered By: rockzxm
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.