how to extract multi level dictionary keys/values in python

南楼画角 提交于 2020-01-17 13:13:36

问题


There is a two level dictionary in python:

for instance here: index[term][id] = n
how to get the term and n when id = 3?

Or it would be perfect if it returns in a form like result[id] = [term, n]


回答1:


Iterate over the nested dict and create new dict to map the values in the desired format. You can create your custom function like:

def get_tuple_from_value(my_dict):
    new_dict = {}
    for term, nested_dict in my_dict.items():
        for id, n in nested_dict.items():
            new_dict[id] = [term, n]
    return new_dict

OR, simple dict comprehension will look like:

{i: [t, n] for t, nd in d.items() for i, n in nd.items()}

where d is holding your dictionary.



来源:https://stackoverflow.com/questions/40657403/how-to-extract-multi-level-dictionary-keys-values-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!