我创建了以下字典: d = {}我添加了一个新密钥和一对作为相应的d['Key1'] = (1, 2)如果我打印字典{'Key1': (1, 2)}
如何将以下词典中的另一对整数添加到以下键中以便使{'Key1': (1, 2), (1, 3), (1, 4)} 。 是否可以在Python中执行此操作? 如果是的话我该怎么办?
我还可以计算与特定键对应的值的数量吗?
I created the following dictionary: d = {} I add to it a new key and a couple as the corresponding d['Key1'] = (1, 2) If I print the dictionarry{'Key1': (1, 2)}
How can I add another pair of integers to the following dictionarry to the following key in order to have {'Key1': (1, 2), (1, 3), (1, 4)}. Is it possible to do it in Python? if yes How can I do it?
Can I also count the number of values that correspond to a specific key?
最满意答案
是的,但是您需要为您的值使用容器。
例如,您可以使用列表,如果您的键具有多个值,也可以使用dict.setdefault方法进行分配,这对于您想要添加具有多个值的另一个键非常有用:
>>> d = {} >>> d.setdefault('Key1',[]).append((1,2)) >>> d {'Key1': [(1, 2)]} >>> d['Key1'].append((1, 3)) >>> d {'Key1': [(1, 2), (1, 3)]} >>> d.setdefault('Key2',[]).append((4,2)) >>> d {'Key2': [(4, 2)], 'Key1': [(1, 2), (1, 3)]}setdefault(key [,default])
如果key在字典中,则返回其值。 如果没有,请插入值为default的值并返回默认值。 默认默认为无。
Yes its possible but you need to use a container for your values.
For example you can use a list,also you can use dict.setdefault method for assignment if your keys will have a multiple values, this is useful of you want to add another key with multiple values :
>>> d = {} >>> d.setdefault('Key1',[]).append((1,2)) >>> d {'Key1': [(1, 2)]} >>> d['Key1'].append((1, 3)) >>> d {'Key1': [(1, 2), (1, 3)]} >>> d.setdefault('Key2',[]).append((4,2)) >>> d {'Key2': [(4, 2)], 'Key1': [(1, 2), (1, 3)]}setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
更多推荐
发布评论