访问字典

时间:2017-03-24 23:03:36

标签: python dictionary data-structures

您好我有一个如下字典:

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'和迈克'应该在最后都包含新制作的密钥。 我知道这会引发错误,但它会让你知道我想要实现的目标。谢谢你的帮助

5 个答案:

答案 0 :(得分:6)

我只想使用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})
>>>

答案 1 :(得分:3)

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

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}}

答案 2 :(得分:0)

正如您所见,

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']

答案 3 :(得分:0)

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)

答案 4 :(得分:0)

示例迭代方法:

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})