【问题标题】:Multiple nested dictionaries within a nested dictionary嵌套字典中的多个嵌套字典
【发布时间】:2018-01-29 19:00:56
【问题描述】:

感谢 SO,我使用以下 DataFrame 中的正确键创建了所需的嵌套字典:

df = pd.DataFrame({'name': ['jake','martin','justin'], 'date': ['6/7/2021','1/1/2031','1/4/2011'], 'country':['Russia','USA','Australia'],
'city 1':['Moscow','New York','Sidney'], 'city 2':['St. Petersburg','Los Angeles','Brisbane'], 'kids':[5,3,1], 'Feature 1':['some','feature','here'], 'Feature 2':['some2','feature2','here2']})

看起来像这样:

   name      country   city 1    city2           kids   Feature1   Feature2   date  
0  jake      Russia    Moscow    St. Petersburg  5       some       some2     1/1/2031
1  martin    USA       New York  Los Angeles     3       feature    feature2  4/4/2021
2  justin    Australia Sidney    Brisbane        1       here       here2     2/3/2015

最终目标:

创建一个如下所示的嵌套字典:

{jake: {'name':'jake', 'Russia': {'city1':'Moscow', 'city2': 'St. Petersburg'}, '5': {'Feature1':'some', 'Feature1':'some2'}, 'date': '1/1/2031'}, martin: {}}

所以我的目标是在嵌套字典中创建嵌套字典,我尝试了不同的方法,包括使用 defaultdict,但不幸的是没有成功。

这是我用来创建具有第一级嵌套的嵌套字典的代码:

{jake: {'name':'jake', 'country':'Russia', 'city1':'Moscow', ...}}

df.set_index('name', inplace=True, drop=False)
d = df.transpose().to_dict()

我也尝试创建一个单独的字典,然后附加它,但没有成功。非常感谢任何帮助。

【问题讨论】:

    标签: python python-3.x pandas dictionary


    【解决方案1】:

    如果我理解正确,也许迭代数据框的行并为字典设置值是一种解决方案:

    for index, row in df.iterrows():
        my_dict[row['name']] = {'name': row['name'],
                                row['country']: {'city 1':row['city 1'], 'city 2':row['city 2']},
                                'kids': row['kids'],
                                'date':row['date'], 
                                'features':[row['Feature 1'], row['Feature 2']]}
    
    my_dict
    

    输出:

    {'jake': {'Russia': {'city 1': 'Moscow', 'city 2': 'St. Petersburg'},
      'date': '6/7/2021',
      'features': ['some', 'some2'],
      'kids': 5,
      'name': 'jake'},
     'justin': {'Australia': {'city 1': 'Sidney', 'city 2': 'Brisbane'},
      'date': '1/4/2011',
      'features': ['here', 'here2'],
      'kids': 1,
      'name': 'justin'},
     'martin': {'USA': {'city 1': 'New York', 'city 2': 'Los Angeles'},
      'date': '1/1/2031',
      'features': ['feature', 'feature2'],
      'kids': 3,
      'name': 'martin'}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 2021-12-20
      • 2022-01-25
      • 2018-10-29
      • 1970-01-01
      • 2012-01-29
      • 2021-01-31
      相关资源
      最近更新 更多