如何从python中的字典中选择深度嵌套的key:values [英] How can I select deeply nested key:values from dictionary in python

查看:141
本文介绍了如何从python中的字典中选择深度嵌套的key:values的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从网站上下载了json数据,我想从嵌套的json中选择特定的key:values.我将json转换为python字典.然后,我使用字典理解来选择嵌套的key:values,但是嵌套太多了,我相信有比单独扩展每个字典更好的方法.我在我的方法中看到了冗余.您能建议一个更好的方法吗?

I have downloaded a json data from a website, and I want to select specific key:values from a nested json. I converted the json to python dictionary. Then I used dictionary comprehension to select the nested key:values , however there are too many nests and I am sure there is a better way than expanding every dictionary separately. I see redundancy in my method. Can you please suggest a better method?

{
    "success": true,
    "payload": {
        "tag": {
            "slug": "python",
            "name": "Python",
            "postCount": 10590,
            "virtuals": {
                "isFollowing": false
            }
        },
        "metadata": {
            "followerCount": 18053,
            "postCount": 10590,
            "coverImage": {
                "id": "1*O3-jbieSsxcQFkrTLp-1zw.gif",
                "originalWidth": 550,
                "originalHeight": 300
            }
        }
    }
}    

我的方法:

从datetime导入datetime,timedelta

from datetime import datetime,timedelta

import json,re

data=r'data.json'
#reads json and converts to dictionary
def js_r(data):
    with open(data, encoding='Latin-1') as f_in:
        return json.load(f_in)

def find_key(obj, key):
    if isinstance(obj, dict):
        yield from iter_dict(obj, key, [])
    elif isinstance(obj, list):
        yield from iter_list(obj, key, [])

def iter_dict(d, key, indices):
    for k, v in d.items():
        if k == key:
            yield indices + [k], v
        if isinstance(v, dict):
            yield from iter_dict(v, key, indices + [k])
        elif isinstance(v, list):
            yield from iter_list(v, key, indices + [k])

def iter_list(seq, key, indices):
    for k, v in enumerate(seq):
        if isinstance(v, dict):
            yield from iter_dict(v, key, indices + [k])
        elif isinstance(v, list):
            yield from iter_list(v, key, indices + [k])
if __name__=="__main__":
    my_dict=js_r(data)
    print ( "This is dictionary for python tag",my_dict)
    keys=my_dict.keys()
    print ("This is the dictionary keys",my_dict.keys())
    my_payload=list(find_key(my_dict,'title'))
    print ("These are my payload",my_payload)
    my_post=iter_dict(my_dict,'User','id')
    print(list(my_post))

推荐答案

我建议您使用python-benedict,它是具有完全 keypath支持和许多实用程序方法的可靠python dict子类.

I suggest you to use python-benedict, a solid python dict subclass with full keypath support and many utility methods.

它提供多种格式的IO支持,包括json.

It provides IO support with many formats, including json.

您可以直接从json文件初始化它:

You can initialize it directly from the json file:

from benedict import benedict

d = benedict.from_json('data.json')

现在您的字典具有键路径支持:

Now your dict has keypath support:

print(d['payload.metadata.coverImage.id'])

# or use get to avoid a possible KeyError
print(d.get('payload.metadata.coverImage.id'))

安装:pip install python-benedict

这里是库存储库和文档: https://github.com/fabiocaccamo/python-benedict

Here the library repository and the documentation: https://github.com/fabiocaccamo/python-benedict

这篇关于如何从python中的字典中选择深度嵌套的key:values的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆