使用python从嵌套字典中获取特定键的值

使用python从嵌套字典中获取特定键的值,python,pandas,dictionary,nested,Python,Pandas,Dictionary,Nested,我正在遍历pandas dataframe中的行,从特定列打印出嵌套字典。我的嵌套字典如下所示: {'dek': "<p>Don't forget to buy a card</p>", 'links': {'edit': {'dev': '//patty-menshealth.feature.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c', 'prod': '//patty-menshealth

我正在遍历pandas dataframe中的行,从特定列打印出嵌套字典。我的嵌套字典如下所示:

{'dek': "<p>Don't forget to buy a card</p>",
 'links': {'edit': {'dev': '//patty-menshealth.feature.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c',
   'prod': '//patty-menshealth.prod.com/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c',
   'stage': '//patty-menshealth.stage.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c'},
  'frontend': {'dev': '//menshealth.feature.net/trending-news/a19521193/fathers-day-weekend-plans/',
   'prod': '//www.menshealth.com/trending-news/a19521193/fathers-day-weekend-plans/',
   'stage': '//menshealth.stage.net/trending-news/a19521193/fathers-day-weekend-plans/'}},
 'header': {'title_color': 1, 'title_layout': 1},
 'sponsor': {'program_type': 1, 'tracking_urls': []},
 'social_dek': "<p>Don't forget to buy a card</p>",
 'auto_social': 0,
 'index_title': "\u200bWeekend Guide: Treat Your Dad Right This Father's Day",
 'short_title': "Treat Your Dad Right This Father's Day",
 'social_title': "\u200bWeekend Guide: Treat Your Dad Right This Father's Day",
 'editors_notes': '<p>nid: 2801076<br>created_date: 2017-06-16 13:00:01<br>compass_feed_date: 2017-06-21 14:01:58<br>contract_id: 40</p>',
 'seo_meta_title': "Treat Your Dad Right This Father's Day\u200b | Men’s Health",
 'social_share_url': '/trending-news/a19521193/fathers-day-weekend-plans/',
 'seo_related_links': {},
 'editor_attribution': 'by',
 'hide_from_homepage': 1,
 'syndication_rights': 3,
 'seo_meta_description': "\u200bFrom gifts to food ideas, we've got your Father's Day covered. Just don't forget to buy him a card."}
如何获取特定键的值?我试图用
print(key[5],value
包含要获取的键的索引,但它给了我一个错误:TypeError:“int”对象不可下标


如何获取值?

对于没有直接解决原始问题表示歉意,但可能值得使用
json\u normalize
将嵌套列“展平”

例如,如果示例数据名为
字典

from pandas.io.json import json_normalize

# Flatten the nested dict, resulting in a DataFrame with 1 row and 23 columns
this_df = json_normalize(dictionary)

# Inspect the resulting columns. Is this structure useful?
this_df.columns
Index(['dek', 'social_dek', 'auto_social', 'index_title', 'short_title',
       'social_title', 'editors_notes', 'seo_meta_title', 'social_share_url',
       'editor_attribution', 'hide_from_homepage', 'syndication_rights',
       'seo_meta_description', 'links.edit.dev', 'links.edit.prod',
       'links.edit.stage', 'links.frontend.dev', 'links.frontend.prod',
       'links.frontend.stage', 'header.title_color', 'header.title_layout',
       'sponsor.program_type', 'sponsor.tracking_urls'],
      dtype='object')
data={'dek':“别忘了买一张卡

”, ‘links’:{'edit':{'dev':'//patty menshhealth.feature.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c’, “prod”:“//patty menshhealth.prod.com/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c”, “stage”:“//patty menshealth.stage.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c”, ‘frontend’:{‘dev’:‘//menshhealth.feature.net/trending news/a19521193/fathers day weekend plannis/’, “prod”:“//www.menshhealth.com/trending news/a19521193/父亲节周末计划/”, 'stage':'//menshhealth.stage.net/trending news/a19521193/fathers day weekend plans/'}, 'header':{'title\u color':1,'title\u layout':1}, “发起人”:{“程序类型”:1,“跟踪URL”:[]}, “社交网站”:“别忘了买张卡”

”, “自动社交”:0, “索引标题”:“\u200b周末指南:在父亲节正确对待你的父亲”, “在父亲节好好对待你的父亲”, “社交标题”:“\u200b周末指南:在父亲节正确对待你的父亲”, “编辑笔记”:“nid:2801076
创建日期:2017-06-16 13:00:01
指南针订阅日期:2017-06-21 14:01:58
合同id:40

”, ‘seo_meta_title’:“在父亲节好好对待你的父亲\u200b |男人的健康”, “社交分享网址”:“/趋势新闻/a19521193/父亲节周末计划/”, “搜索引擎优化相关链接”:{}, “编者署名”:“作者”, “从主页隐藏”:1, “银团权利”:3, ‘seo_meta_description’:“\u200b从礼物到食物创意,我们已经涵盖了你父亲节。只是别忘了给他买张贺卡。”} def findValByKey(键:str,数据:dict,级别=0): 对于data.keys()中的i: 打印(“{}{}”。格式(级别*'-',i)) 如果i==键: 打印('---已找到--') 返回数据[键] elif isinstance(数据[i],目录): res=findValByKey(键,数据[i],级别+1) 如果有的话: 返回res 打印(findValByKey(“标题颜色”,数据))
from pandas.io.json import json_normalize

# Flatten the nested dict, resulting in a DataFrame with 1 row and 23 columns
this_df = json_normalize(dictionary)

# Inspect the resulting columns. Is this structure useful?
this_df.columns
Index(['dek', 'social_dek', 'auto_social', 'index_title', 'short_title',
       'social_title', 'editors_notes', 'seo_meta_title', 'social_share_url',
       'editor_attribution', 'hide_from_homepage', 'syndication_rights',
       'seo_meta_description', 'links.edit.dev', 'links.edit.prod',
       'links.edit.stage', 'links.frontend.dev', 'links.frontend.prod',
       'links.frontend.stage', 'header.title_color', 'header.title_layout',
       'sponsor.program_type', 'sponsor.tracking_urls'],
      dtype='object')
data={'dek': "<p>Don't forget to buy a card</p>",
'links': {'edit': {'dev': '//patty-menshealth.feature.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c',
'prod': '//patty-menshealth.prod.com/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c',
'stage': '//patty-menshealth.stage.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c'},
'frontend': {'dev': '//menshealth.feature.net/trending-news/a19521193/fathers-day-weekend-plans/',
'prod': '//www.menshealth.com/trending-news/a19521193/fathers-day-weekend-plans/',
'stage': '//menshealth.stage.net/trending-news/a19521193/fathers-day-weekend-plans/'}},
'header': {'title_color': 1, 'title_layout': 1},
'sponsor': {'program_type': 1, 'tracking_urls': []},
'social_dek': "<p>Don't forget to buy a card</p>",
'auto_social': 0,
'index_title': "\u200bWeekend Guide: Treat Your Dad Right This Father's Day",
'short_title': "Treat Your Dad Right This Father's Day",
'social_title': "\u200bWeekend Guide: Treat Your Dad Right This Father's Day",
'editors_notes': '<p>nid: 2801076<br>created_date: 2017-06-16 13:00:01<br>compass_feed_date: 2017-06-21 14:01:58<br>contract_id: 40</p>',
'seo_meta_title': "Treat Your Dad Right This Father's Day\u200b | Men’s Health",
'social_share_url': '/trending-news/a19521193/fathers-day-weekend-plans/',
'seo_related_links': {},
'editor_attribution': 'by',
'hide_from_homepage': 1,
'syndication_rights': 3,
'seo_meta_description': "\u200bFrom gifts to food ideas, we've got your Father's Day covered. Just don't forget to buy him a card."}

def findValByKey(key:str, data:dict, level=0):
    for i in data.keys():
        print("{} {}".format(level*'-', i))
        if i==key:
            print('---found---')
            return data[key]
        elif isinstance(data[i], dict):
            res = findValByKey(key, data[i], level+1)
            if res:
                return res


print(findValByKey('title_color', data))