Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...