简体   繁体   中英

Accessing values in a sub-dictionary within a dictionary

Hello I have a dictionary that looks like this:

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

I want to gain access and extract the keys within the sub-dictionary and assign them to variables like this:

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

Now, when I run the variables above I get a 'Key Error'. It is understandable because I need to first access the outer dictionary. I would appreciate if someone gave a helping hand on how to access keys and the values within the sub-dictionary as those are the values I want to use.

Also i would like to do create a new key, this may not be right but something on these lines:

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

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

I want to be able to access all those keys in the dictionary and create a new key. The outer keys such as "John' and 'Mike' should both contain the newly made key at the end. I know this throws an error but it will give you an idea on what I want to achieve. Thanks for the help

I would just use a Counter object to get the totals:

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

This has the added benefit of working nicely even if the keys aren't always present.

If you want the total assets, you can then simply sum the values:

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

To sum the total assets for each person and add it as a new key:

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

which will result in:

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

dictionary doens't have a key car , as you've seen. But dictionary['John'] does.

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

The value associated with each key in dictionary is, itself, another dictionary, which you index separately. There is no single object that contains, eg, the car value for each subdictionary; you have to iterate over each value.

# 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())

or

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

Sample iteration method:

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

print(totals)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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