访问字典中子字典内的值

3

你好,我有一个像这样的字典:

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”这样的外部键都应该在末尾包含新创建的键。 我知道这会引发错误,但它会给你一个想要实现的想法。感谢您的帮助。


内部键总是可用吗? - undefined
做什么?除了如何访问一个值之外,你还没有指定任何东西。 - undefined
我不清楚你想要实现什么。你应该在问题中用例子详细解释一下... - undefined
1
为什么你不直接写下你想要的结果呢? - undefined
1
@DeepakM 看看我的回答。这是一个相当典型的XY问题 - undefined
显示剩余9条评论
5个回答

6
为每个人的总资产汇总,然后添加为一个新的键:
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}}

1
为终于弄清楚原帖作者想要的内容点赞。 - undefined
很抱歉解释起来有点困难,但还是非常感谢你的帮助!@juanpa.arrivillaga - undefined
1
@DeepakM 请仔细审查一下[ask]和[mcve],这样下次就会更清楚明了。 - undefined
1
sum(value for (key, value) in dictionary[person].items() if key != 'boat') - undefined
如果你想创建一个包含特定值的列表,可以使用 if key in ['car', 'house'] - undefined
显示剩余2条评论

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

计数器在这里真的很方便... :D - undefined
1
@repzero 是的,Counter 在很多时候非常方便。 - undefined
1
正如最初所问,这是最好的解决方案。并且额外奖励他为了搞清楚他真正的问题而付出的努力。 - undefined

0

dictionary 没有一个叫做 car 的键,就像你看到的那样。但是 dictionary['John'] 有。

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

每个键在字典中关联的值本身是另一个字典,你需要单独索引。没有一个单独的对象包含了每个子字典中的"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']

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)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接