Skip to main content
 首页 » 编程设计

python之嵌套字典中的多个嵌套字典

2024年10月01日8shanyou

多亏了 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() 

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

请您参考如下方法:

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

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'}}