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