python 来自键路径的嵌套字典值

gajydyqb  于 2022-12-28  发布在  Python
关注(0)|答案(9)|浏览(178)

在key path的帮助下从嵌套字典中获取值,下面是dict

json = {
    "app": {
        "Garden": {
            "Flowers": {
                "Red flower": "Rose",
                "White Flower": "Jasmine",
                "Yellow Flower": "Marigold"
            }
        },
        "Fruits": {
            "Yellow fruit": "Mango",
            "Green fruit": "Guava",
            "White Flower": "groovy"
        },
        "Trees": {
            "label": {
                "Yellow fruit": "Pumpkin",
                "White Flower": "Bogan"
            }
        }
    }

该方法的输入参数是用点分隔的关键路径,从关键路径=“app.Garden.Flowers.白色Flower”需要打印'Jasmine'。

import json
with open('data.json') as data_file:    
  j = json.load(data_file)

def find(element, JSON):     
  paths = element.split(".")  
  # print JSON[paths[0]][paths[1]][paths[2]][paths[3]]
  for i in range(0,len(paths)):
    data = JSON[paths[i]]
    # data = data[paths[i+1]]
    print data


find('app.Garden.Flowers.White Flower',j)
06odsfpq

06odsfpq1#

这是fold的一个示例,你可以这样简洁地写它:

from functools import reduce
import operator

def find(element, json):
    return reduce(operator.getitem, element.split('.'), json)

或者更Python化一些(因为reduce()由于可读性差而不受欢迎),如下所示:

def find(element, json):
    keys = element.split('.')
    rv = json
    for key in keys:
        rv = rv[key]
    return rv

j = {"app": {
    "Garden": {
        "Flowers": {
            "Red flower": "Rose",
            "White Flower": "Jasmine",
            "Yellow Flower": "Marigold"
        }
    },
    "Fruits": {
        "Yellow fruit": "Mango",
        "Green fruit": "Guava",
        "White Flower": "groovy"
    },
    "Trees": {
        "label": {
            "Yellow fruit": "Pumpkin",
            "White Flower": "Bogan"
        }
    }
}}
print find('app.Garden.Flowers.White Flower', j)
flvtvl50

flvtvl502#

我也遇到过类似的情况,发现了这个dpath module。又好又容易。

wxclj1h5

wxclj1h53#

我建议您使用python-benedict,它是一个python dict子类,具有完全的keypath支持和许多实用方法。
您只需要发布现有的命令:

d = benedict(json)
# now your keys support dotted keypaths
print(d['app.Garden.Flower.White Flower'])

这里的库和文档:https://github.com/fabiocaccamo/python-benedict
注:本人是本项目的作者

ca1c2owp

ca1c2owp4#

您的代码很大程度上依赖于键名中没有出现任何点,您可能能够控制这一点,但不一定。
我会选择使用元素名称列表的通用解决方案,然后生成列表,例如,通过拆分键名称的虚线列表:

class ExtendedDict(dict):
    """changes a normal dict into one where you can hand a list
    as first argument to .get() and it will do a recursive lookup
    result = x.get(['a', 'b', 'c'], default_val)
    """
    def multi_level_get(self, key, default=None):
        if not isinstance(key, list):
            return self.get(key, default)
        # assume that the key is a list of recursively accessible dicts
        def get_one_level(key_list, level, d):
            if level >= len(key_list):
                if level > len(key_list):
                    raise IndexError
                return d[key_list[level-1]]
            return get_one_level(key_list, level+1, d[key_list[level-1]])

        try:
            return get_one_level(key, 1, self)
        except KeyError:
            return default

    get = multi_level_get # if you delete this, you can still use the multi_level-get

一旦你有了这个类,就很容易转换你的法令并获得“茉莉花”:

json = {
        "app": {
            "Garden": {
                "Flowers": {
                    "Red flower": "Rose",
                    "White Flower": "Jasmine",
                    "Yellow Flower": "Marigold"
                }
            },
            "Fruits": {
                "Yellow fruit": "Mango",
                "Green fruit": "Guava",
                "White Flower": "groovy"
            },
            "Trees": {
                "label": {
                    "Yellow fruit": "Pumpkin",
                    "White Flower": "Bogan"
                }
            }
        }
    }

j = ExtendedDict(json)
print j.get('app.Garden.Flowers.White Flower'.split('.'))

将为您提供:

Jasmine

与来自dict的普通get()类似,如果指定的键(列表)在树中不存在,则会得到None,并且可以指定第二个参数作为返回值,而不是None

cmssoen2

cmssoen25#

非常接近了。你需要(正如你在评论中所说的)递归地遍历JSON主对象。你可以通过存储最外层键/值的结果,然后使用它来获得下一个键/值,等等,直到你没有路径为止。

def find(element, JSON):     
  paths = element.split(".")
  data = JSON
  for i in range(0,len(paths)):
    data = data[paths[i]]
  print data

不过,您仍然需要注意KeyErrors。

aamkag61

aamkag616#

一行程序:

from functools import reduce

a = {"foo" : { "bar" : "blah" }}
path = "foo.bar"

reduce(lambda acc,i: acc[i], path.split('.'), a)
nbnkbykc

nbnkbykc7#

    • 选项1:Cisco提供的pyats库[其a c扩展名]**
  • 它的快速和超快(测量它的时间,如果需要)
  • 类似Javascript的用法[括号查找、点查找、组合查找]
  • 缺少键的点查找引发属性错误,括号或默认python dict查找给出KeyError。
pip install pyats pyats-datastructures pyats-utils
from pyats.datastructures import NestedAttrDict
item = {"specifications": {"os": {"value": "Android"}}}
path = "specifications.os.value"
x = NestedAttrDict(item)
print(x[path])# prints Android
print(x['specifications'].os.value)# prints Android
print(x['specifications']['os']['value'])#prints Android
print(x['specifications'].os.value1)# raises Attribute Error
    • 备选案文2:税、效用税**
  • 超快(如果需要,用timeit测量)
from pyats.utils import utils
item = {"specifications": {"os": {"value": "Android"}}}
path = "specifications.os.value"
path1 = "specifications.os.value1"
print(utils.chainget(item,path))# prints android (string version)
print(utils.chainget(item,path.split('.')))# prints android(array version)
print(utils.chainget(item,path1))# raises KeyError
    • 选项3:不带外部库的python**

1.与lambda相比速度更快。
1.在lambda和其他情况下不需要单独的错误处理。
1.可读性和简洁性可以成为项目中的实用程序功能/帮助器

from functools import reduce
item = {"specifications": {"os": {"value": "Android"}}}
path1 = "specifications.family.value"
path2 = "specifications.family.value1"

def test1():
    print(reduce(dict.get, path1.split('.'), item))

def test2():
    print(reduce(dict.get, path2.split('.'), item))

test1() # prints Android
test2() # prints None
unguejic

unguejic8#

编写了在dict中处理列表的函数。

d = {'test': [
    {'value1': 'val'},
    {'value1': 'val2'}]}

def find_element(keys: list, dictionary: dict):
    rv = dictionary
    if isinstance(dictionary, dict):
        rv = find_element(keys[1:], rv[keys[0]])
    elif isinstance(dictionary, list):
        if keys[0].isnumeric():
            rv = find_element(keys[1:], dictionary[int(keys[0])])
    else:
        return rv
    return rv

val = find_element('test.1.value1'.split('.'), d)
kzmpq1sx

kzmpq1sx9#

data = {
    "data": {
        "author_id": "1",
        "text": "hi msg",
        "attachments": {
            "media_keys": [
                "3_16"
            ]
        },
        "id": "2",
        "edit_history_tweet_ids": [
            "2"
        ]
    },
    "includes": {
        "media": [
            {
                "media_key": "3_16",
                "height": 500,
                "type": "photo",
                "width": 500,
                "url": "https://pbs.twimg.com/media/xxxxxx.png"
            }
        ],
        "users": [
            {
                "id": "1",
                "name": "name1",
                "username": "username1"
            }
        ]
    }
}

def get_value_from_dict(dic_obj, keys: list, default):
    """
    get value from dict with key path.
    :param dic_obj: dict
    :param keys: dict key
    :param default: default value
    :return:
    """
    if not dic_obj or not keys:
        return default

    pre_obj = dic_obj
    for key in keys:
        t = type(pre_obj)
        if t is dict:
            pre_obj = pre_obj.get(key)
        elif (t is list or t is tuple) and str(key).isdigit() and len(pre_obj) > int(key):
            pre_obj = pre_obj[int(key)]
        else:
            return default
    return pre_obj


print('media_key:', get_value_from_dict(data, 'data.attachments.media_keys'.split('.'), None))
print('username:', get_value_from_dict(data, 'includes.users.0.username'.split('.'), None))

media_key: ['3_16']
username: username1

相关问题