簡體   English   中英

python中的嵌套列表和字典

[英]Nested lists and dictionaries in python

我在 python 中有 3 個不同的字典,像這樣

d1 = {'simple_key':'hello'}
d2 = {'k1':{'k2':'hello'}}
d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]}

我想從這些詞典中提取“你好”這個詞。 但是我面臨的問題是我想找到一種通用的方法來提取它。 我該怎么做?

要使用值獲取字典中的關鍵路徑,您可以將其展平為 json。

>>> from json_flatten import flatten
>>> d1 = {'simple_key':'hello'}
>>> d2 = {'k1':{'k2':'hello'}}
>>> d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]}
>>> flatten(d2)
{'k1.k2': 'hello'}
>>> flat = flatten(d3)
{'k1.0.nest_key.0': 'this is deep', 'k1.0.nest_key.1.0': 'hello'}

要找到匹配的鍵,請使用,

>>> [k for k, v in flat.items() if v == 'hello']
['k1.0.nest_key.1.0']

JSON 扁平化

您可以繼續進入字典,直到找到一個值,而不是字典。 遞歸在這里會有所幫助:

def get_value(dict):
     dict_value = list(dict.values())[0]
     if type(dict_value) is dict:
          get_value(dict_value)
     else: 
          return dict_value

可能有更好的方法來做dict_value = list(dict.values())[0]但現在沒有想到

您可以制作自己的 flattener 函數,該函數產生 dict 中的值和列表成員:

def is_nonstring_iterable(x):
    return ((hasattr(x, "__iter__") or hasattr(x, "__getitem__")) 
        and not isinstance(x, str))

def flatten(thing):
    """ Recursively iterate through values in dictionary-like object or members 
        in lists, tuples or other non-string iterables """
    if hasattr(thing, "values"):
        thing = thing.values()
    if is_nonstring_iterable(thing):
        for element in thing:
            yield from flatten(element)
    else:
        yield thing

for d in [d1, d2, d3]:
    print(list(flatten(d)))
    print(any(item == "hello" for item in flatten(d))) # returns whether hello is found

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM