繁体   English   中英

访问词典中的子词典中的值

[英]Accessing values in a sub-dictionary within a dictionary

您好,我有一本看起来像这样的字典:

dictionary = {'John': {'car':12, 'house':10, 'boat':3},
              'Mike': {'car':5, 'house':4, 'boat':6}}

我想获得访问权限并提取子词典中的键,并将其分配给这样的变量:

cars_total = dictionary['car']
house_total = dictionary['house']
boat_total = dictionary['boat']

现在,当我运行上面的变量时,我得到一个“关键错误”。 这是可以理解的,因为我需要首先访问外部字典。 如果有人在如何访问子词典中的键和值方面提供了帮助,我将不胜感激,因为这些正是我要使用的值。

我也想创建一个新的密钥,这可能不正确,但在以下几行中:

    car = dictionary['car']
    house = dictionary['house']
    boat = dictionary['boat']

dictionary['total_assets'] = car + house + boat 

我希望能够访问字典中的所有那些键并创建一个新键。 外键(例如“ John”和“ Mike”)都应在末尾都包含新创建的键。我知道这会引发错误,但会为您提供我要实现的目标的想法。感谢您的帮助

我只是使用Counter对象来获取总数:

>>> from collections import Counter
>>> totals = Counter()
>>> for v in dictionary.values():
...     totals.update(v)
...
>>> totals
Counter({'car': 17, 'house': 14, 'boat': 9})
>>> totals['car']
17
>>> totals['house']
14
>>>

即使键并不总是存在,这也具有很好地工作的好处。

如果需要总资产,则可以简单地将值求和:

>>> totals['total_assets'] = sum(totals.values())
>>> totals
Counter({'total_assets': 40, 'car': 17, 'house': 14, 'boat': 9})
>>>

汇总每个人的总资产并将其添加为新键:

for person in dictionary:
    dictionary[person]['total_assets'] = sum(dictionary[person].values())

这将导致:

dictionary = {'John': {'car':12, 'house':10, 'boat':3, 'total_assets':25},
              'Mike': {'car':5, 'house':4, 'boat':6, 'total_assets':15}}

如您所见, dictionary没有钥匙car 但是dictionary['John']可以。

$ >>> dictionary['John']
{'car': 12, 'boat': 3, 'house': 10}
>>> dictionary['John']['car']
12
>>> 

dictionary每个键相关联的值本身就是另一个字典,您可以分别对其进行索引。 没有单个对象包含例如每个子类的car价值。 您必须遍历每个值。

# Iterate over the dictionary once per aggregate
cars_total = sum(d['car'] for d in dictionary.values())
house_total = sum(d['house'] for d in dictionary.values())
boat_total = sum(d['boat'] for d in dictionary.values())

要么

# Iterate over the dictionary once total
cars_total = 0
house_total = 0
boat_total = 0
for d in dictionary.values():
    cars_total += d['car']
    house_total += d['house']
    boat_total += d['boat']
dictionary = {'John': {'car':12, 'house':10, 'boat':3},'Mike': {'car':5, 'house':4, 'boat':6}}
total_cars=sum([dictionary[x]['car'] for x in dictionary ])
total_house=sum([dictionary[x]['house'] for x in dictionary ])
total_boats=sum([dictionary[x]['boat'] for x in dictionary ])
print(total_cars)
print(total_house)
print(total_boats)

样本迭代方法:

from collections import defaultdict
totals = defaultdict(int)
for person in dictionary:
    for element in dictionary[person]:
        totals[element] += dictionary[person][element]

print(totals)

输出:

defaultdict(<type 'int'>, {'car': 17, 'boat': 9, 'house': 14})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM