如何在python中添加一对字典?(How to add a pair to a dictionary in python?)

编程入门 行业动态 更新时间:2024-10-21 10:29:16
如何在python中添加一对字典?(How to add a pair to a dictionary in python?)

我创建了以下字典: 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.

更多推荐

本文发布于:2023-07-06 07:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   如何在   python   dictionary   add

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!