我有兩個字典命名為,可以說,a = {'A':{2021:45.65},'B':{2021:56.34}}
和b = {'A':{2021:78.67},'B':{2021:87.54}}
我想從 A 和 B 的“子字典”中獲取值,并計算第二個字典中的值占第一個字典的值的百分比。
我似乎無法弄清楚如何從不同的字典訪問浮點值并計算結果。
--------------------------更新----------- -
抱歉沒有以適當的方式理解我的問題。我想出了一種方法來做到這一點,如果您認為它仍然存在問題,請務必提及。
dict_keys = ['A','B']
for x in dict_keys:
val1 = a[x].values()
val2 = b[x].values()
uj5u.com熱心網友回復:
正如一些評論中提到的那樣,將其分解為邏輯部分/步驟會很有幫助。
//pseudocode
if the len of a == len of b:
for key, value in a:
if the len of a[key] == len of b[key]:
for key, value in a[key]:
more_less = a's key's value divided by b's key's value
任何人在這里谷歌搜索的正確代碼:
# [partially] confirming data integrity - you can do more here if needed
lf len(a) == len(b):
# iterate through each dictionary in `a` to compare to the associated dictionary in `b`
for key, value in a:
# [partially] confirming data integrity of the 'child' dictionaries
if len(value) == len(b[key]):
for key2, value2 in a[key]:
# key2 is, in this case, '2021'; value2 is the number
more_less = value2 / b[key][key2]
# We'll print the result here, you can also use string formatting, of course, but to keep it as the most basic level:
print(str(b[key][key2]) " is " str(more_less) "% of " value2 ".")
uj5u.com熱心網友回復:
如果您保證 a 和 b 的 dicts 結構完全相同,您可以簡單地遍歷一個并使用密鑰訪問另一個,但這是一種相當薄弱的方法。
result = {}
for key, item in a.items():
for nest_key, nest_item in a[key].items():
result[key] = nest_item / b[key][nest_key]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/469291.html
上一篇:以串列為值的字典
下一篇:基于元組值的嵌套字典的元組串列