如何添加到python字典而不替换 [英] How to add to python dictionary without replacing

查看:313
本文介绍了如何添加到python字典而不替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前的代码是 category1 [name] =(number)但是,如果同一个名字出现,字典中的值将被新的数字替换为我这样做,而不是被替换的值被保留,并且新的值也被添加,现在给出关键的两个值,谢谢。

the current code I have is category1[name]=(number) however if the same name comes up the value in the dictionary is replaced by the new number how would I make it so instead of the value being replaced the original value is kept and the new value is also added, giving the key two values now, thanks.

推荐答案

您必须使字典指向列表而不是数字,例如,如果您有两个数字类别 cat1

You would have to make the dictionary point to lists instead of numbers, for example if you had two numbers for category cat1:

categories["cat1"] = [21, 78]

为了确保您将新的数字添加到列表中而不是替换它们,请先添加新数字,然后再添加它们:

To make sure you add the new numbers to the list rather than replacing them, check it's in there first before adding it:

cat_val = # Some value
if cat_key in categories:
    categories[cat_key].append(cat_val)
else:
    # Initialise it to a list containing one item
    categories[cat_key] = [cat_val]

要访问值,您只需使用类别[cat_key] 将返回 [12] ,如果有一个键值为12,和 [12,95] 如果该键有两个值。

To access the values, you simply use categories[cat_key] which would return [12] if there was one key with the value 12, and [12, 95] if there were two values for that key.

请注意,如果你不想存储重复的键,您可以使用一个集合而不是列表:

Note that if you don't want to store duplicate keys you can use a set rather than a list:

cat_val = # Some value
if cat_key in categories:
    categories[cat_key].add(cat_val)
else:
    # Initialise it to a set containing one item
    categories[cat_key] = set(cat_val)

这篇关于如何添加到python字典而不替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆