简体   繁体   English

Python:将列表添加到现有字典中吗?

[英]Python: Append a list to an existing dictionary?

I have a dictionary with an int as value for each key. 我有一本字典,每个键都有一个int作为值。 I also have total stored in a variable. 我也有总计存储在一个变量中。 I want to obtain a percentage that each value represent for the variable and return the percentage to the dictionary as another value for the same key. 我想获取每个值代表该变量的百分比,并将该百分比作为同一键的另一个值返回到字典中。

I tried to extract the values in a list, then do the operation and append the results to another list. 我尝试提取列表中的值,然后执行操作并将结果附加到另一个列表中。 But I don't know how to append that list to the dictionary. 但是我不知道如何将该列表附加到字典中。

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

You're better off avoiding the intermediate list and just updating each key as you go: 最好避免使用中间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]

While it's technically possible to zip the dict 's keys with the values of the list , as long as the keys aren't changed and the list order is kept in line with the values extracted from the dict , the resulting code would reek of code smell, and it's just easier to avoid that list entirely anyway. 从技术上讲,可以使用list的值对dict的键进行zip ,但只要不更改键且list顺序与从dict提取的值保持一致,则生成的代码就会很烂气味,总之完全避免该list更容易。

Note that this won't put a % sign in the representation, because there is no such thing as a percentage type. 请注意,这不会在表示中添加%符号,因为不存在百分比类型之类的东西。 The only simple way to shove one in there would be to store it as a string, not a float , eg replacing the final line with: 推入其中的唯一简单方法是将其存储为字符串,而不是float ,例如,将最后一行替换为:

    d[k] = [f'{100 * (v / total)}%', v]

to format the calculation as a string, and shove a % on the end. 将计算结果格式化为字符串,并在末尾加%

Here 这里

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)

output 产量

{'key_1': ['15.0%', 150], 'key_2': ['35.0%', 350], 'key_3': ['50.0%', 500]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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