本文介绍了如何从元组(或2个列表)更新字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为可以如下更新现有字典:

I thought it would be possible to update an existing dictionary as follows:

nameValuePair = 'myKey=myValue'
d.update(nameValuePair.split('='))

但是我收到此错误:

Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    d2.update(item.split('='))
ValueError: dictionary update sequence element #0 has length 1; 2 is required

我查看了有关此主题的其他StackOverflow问题/答案,这使我认为这是可能的.我一定缺少基本的东西...

I looked at some other StackOverflow questions/answers on this topic, which made me think this was possible. I must be missing something basic...

推荐答案

该错误消息已经为您提供了提示:您传递的序列中的每个项目的长度都必须为2,这意味着它必须包含一个键和一个值.

The error message already gives you a hint: Each item in the sequence you pass must have a length of 2, meaning it has to consist of a key and a value.

因此,您必须传递2个元组(-lists,-sequences等)的元组(list,sequence ...):

Therefore you have to pass a tuple (list, sequence,...) of 2-tuples (-lists, -sequences,...):

// the value passed will be ((myKey, myValue), )
d.update((nameValuePair.split('='), ))
//       ^                        ^ ^
// creates a tuple of 1 element

或者,您可以执行以下操作:

Alternatively you could do:

key, value = nameValuePair.split('=')
d[key] = value

这篇关于如何从元组(或2个列表)更新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 05:02