![](/img/trans.png)
[英]Append value to list in dictionary with existing or non-existing key in Python
[英]Python: Append a list to an existing dictionary?
我有一本字典,每個鍵都有一個int作為值。 我也有總計存儲在一個變量中。 我想獲取每個值代表該變量的百分比,並將該百分比作為同一鍵的另一個值返回到字典中。
我嘗試提取列表中的值,然后執行操作並將結果附加到另一個列表中。 但是我不知道如何將該列表附加到字典中。
total = 1000
d = {"key_1":150, "key_2":350, "key_3":500}
lst = list(d.values())
percentages = [100 * (i/total) for i in lst]
# Desired dictionary
d
{"key_1": [15%, 150],
"key_2": [35%, 350],
"key_3": [50%, 500]
}
最好避免使用中間list
而只需在運行時更新每個鍵:
total = 1000
d = {"key_1":150, "key_2":350, "key_3":500}
for k, v in d.items():
d[k] = [100 * (v / total), v]
從技術上講,可以使用list
的值對dict
的鍵進行zip
,但只要不更改鍵且list
順序與從dict
提取的值保持一致,則生成的代碼就會很爛氣味,總之完全避免該list
更容易。
請注意,這不會在表示中添加%
符號,因為不存在百分比類型之類的東西。 推入其中的唯一簡單方法是將其存儲為字符串,而不是float
,例如,將最后一行替換為:
d[k] = [f'{100 * (v / total)}%', v]
將計算結果格式化為字符串,並在末尾加%
。
這里
total = 1000
d = {"key_1": 150, "key_2": 350, "key_3": 500}
d1 = {k: ['{}%'.format(v * 100 / 1000),v] for k, v in d.items()}
print(d1)
產量
{'key_1': ['15.0%', 150], 'key_2': ['35.0%', 350], 'key_3': ['50.0%', 500]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.