Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向具有自动递增值的字典添加键_Python - Fatal编程技术网

Python 向具有自动递增值的字典添加键

Python 向具有自动递增值的字典添加键,python,Python,我有一个字典d,3个键的值为0,1,2: {'-11111': 0, 'hello kitty': 1, 'hello this is me': 2} 我想从列表中添加两个新键,并自动将它们的值增加为3和4 我能走这么远 newkeys = ['give a dog a bone', 'take a dog for a walk'] d.update([newkeys]) 提供更新的字典,但没有为新键指定值 {'-11111': 0, 'hello kitty': 1, 'hello t

我有一个字典d,3个键的值为0,1,2:

{'-11111': 0, 'hello kitty': 1, 'hello this is me': 2}
我想从列表中添加两个新键,并自动将它们的值增加为3和4

我能走这么远

newkeys = ['give a dog a bone', 'take a dog for a walk']
d.update([newkeys])
提供更新的字典,但没有为新键指定值

{'-11111': 0,
 'hello kitty': 1,
 'hello this is me': 2,
 'give a dog a bone': 'take a dog for a walk'}
我想要的是:

{'-11111': 0,
 'hello kitty': 1,
 'hello this is me': 2,
 'give a dog a bone': 3,
 'take a dog for a walk': 4}
有没有一种有效而简单的方法来做到这一点?
谢谢

您可以反复浏览
新键列表
,并将每个新键设置为
目录中当前项目列表的长度

d={'-11111':0,“hello kitty”:1,“你好,这是我”:2}
newkeys=[“给狗一根骨头”,“带狗散步”]
newkeys=[“给狗一根骨头”,“带狗散步”]
对于输入新密钥:
d[key]=len(d.items())

要添加新键,只需使用
d[keyname]=keyvalue
,键就会被追加

另一个选项,假设您不希望从0开始(但希望递增)


考虑到您确切地知道键和值应该是什么,为什么不执行以下操作:

newkeys = [['give a dog a bone', 3], ['take a dog for a walk', 4]]
d.update(newkeys)
在每个子列表中,第一项成为键,第二项成为关联值

编辑:

同样的想法,具有增量功能

d = {'-11111': 0, 'hello kitty': 1, 'hello this is me': 2}
newkeys = ['give a dog a bone', 'take a dog for a walk']
d.update([[x, y + len(d)] for y, x in enumerate(newkeys)])
# {'-11111': 0, 'hello kitty': 1, 'hello this is me': 2,
#  'give a dog a bone': 3, 'take a dog for a walk': 4}

@MichaelK您可以使用列表来保存
dict.update
逻辑。见下面我的答案。
d = {'-11111': 0, 'hello kitty': 1, 'hello this is me': 2}
newkeys = ['give a dog a bone', 'take a dog for a walk']
d.update([[x, y + len(d)] for y, x in enumerate(newkeys)])
# {'-11111': 0, 'hello kitty': 1, 'hello this is me': 2,
#  'give a dog a bone': 3, 'take a dog for a walk': 4}