嵌套字典获取内部值

2024-10-03 17:19:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道当你在字典里有一个字典的时候,如何根据“两个”键得到值。 i、 电子邮件:

street_dict ={"streetA": ["HouseA1", "HouseA2"],
              "streetB": ["HouseB1", "HouseB2"]}

house_dict = {"HouseA1" : ["Jack", "Jones", "Joel"],
              "HouseA2" : ["Paul", "Lucas", "Martin"],
              "HouseB1" : ["Rick", "Jordan", "Michael"],
              "HouseB2" : ["Peter", "George", "Toni"]}
  • 如何找到瑞克住的地方?(房屋和街道)
  • 最快的办法是什么?你知道吗

Tags: street字典电子邮件dicthousejackjoeljones
3条回答

找到瑞克。不使用列表理解:

def find_person(name):
    for house, persons in house_dict.items():
        if name in persons:
            for street, houses in street_dict.items():
                if house in houses:
                    print("{} lives at {} {}".format(name, house, street))

让所有人都站在一条街上:

def get_persons(street):
    persons = []
    for house in street_dict.get(street, []):
        persons.extend(house_dict.get(house, []))
    return persons

您可以将数据重建到更合适的字典中

hs = {house:street for street,houses in street_dict.items() for house in houses}
s = {person: {'street':hs[house], 'house':house} for house, persons in house_dict.items() for person in persons}
# {'Jack': {'street': 'streetA', 'house': 'HouseA1'}, 'Jones': {'street': 'streetA', 'house': 'HouseA1'},..

那么您的查询将是

# where lives Jordan    
print(s['Jordan'])
# all persons of StreetA
print([person for person, address in s.items() if address['street'] == 'streetA'])
  • How to find out where Rick lives? (House and Street)

您可以使用列表:

[(hs,st) for st, j in street_dict.items() for hs in j if 'Rick' in set(house_dict[hs])]
# [('HouseB1', 'streetB')]
  • Whats the fastest way to get all persons of StreetA?

与上述方法类似:

from itertools import chain

list(chain.from_iterable([house_dict[house] for house in street_dict["streetA"]]))
# ['Jack', 'Jones', 'Joel', 'Paul', 'Lucas', 'Martin']

相关问题 更多 >