[英]How to add a 2-element list to a python dictionary as a key/value pair?
I want to add the content of a 2-element list to a python dictionary (python3).我想将 2 元素列表的内容添加到 python 字典 (python3)。 The first element is the key, the second element is the value.
第一个元素是键,第二个元素是值。
I followed this documentation but maybe I misunderstood the content.我遵循了这个文档,但也许我误解了内容。
Here is what I am trying to do这是我想要做的
mydict = {"test": "1"}
key_value_pair = ["test2", "42"]
mydict.update(key_value_pair)
with the expected result to have a dict with two entries:预期结果是一个包含两个条目的字典:
{
"test": "1",
"test2" : "42"
}
but instead I get an error ValueError: dictionary update sequence element #0 has length 5; 2 is required
但是我得到一个错误
ValueError: dictionary update sequence element #0 has length 5; 2 is required
ValueError: dictionary update sequence element #0 has length 5; 2 is required
. ValueError: dictionary update sequence element #0 has length 5; 2 is required
。
Sure I can do it as follows:当然我可以这样做:
mydict[key_value_pair[0]] = key_value_pair[1]
but the idea is to split a string and use the two elements directly as key/value pair:但想法是拆分一个字符串并直接使用两个元素作为键/值对:
mystring = "test2=42"
mydict.update(mystring.split("="))
instead of代替
mystring = "test4=42"
splitted_string = mystring.split("=")
mydict[splitted_string[0]] = splitted_string[1]
I hope you see the point...我希望你明白这一点......
Update the dictionary with the key/value pairs from other, overwriting existing keys.
使用其他键/值对更新字典,覆盖现有键。 Return None.
返回无。
update()
accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two).update()
接受另一个字典对象或键/值对的可迭代对象(作为元组或其他长度为 2 的可迭代对象)。 If keyword arguments are specified, the dictionary is then updated with those key/value pairs:d.update(red=1, blue=2)
.如果指定了关键字参数,则会使用这些键/值对更新字典:
d.update(red=1, blue=2)
。
So when you provide an iterable
, it expects each element of the iterable to be a key-value pair.因此,当您提供一个
iterable
,它希望iterable
每个元素都是一个键值对。
That's why this works:这就是为什么这有效:
kvp = ["newkey", "newval"]
mydict.update([kvp])
Each element of the input iterable is a 2-element list.输入可迭代对象的每个元素都是一个 2 元素列表。
When you do just当你只做
mydict.update(kvp)
update()
tries to ensure that each element of kvp
is a 2-element iterable. update()
尝试确保kvp
每个元素都是 2 元素可迭代的。 Since strings are iterable, you get the error that the length of the element is invalid.由于字符串是可迭代的,您会收到元素长度无效的错误。
Side note: if kvp
contained integers, or something that isn't iterable:旁注:如果
kvp
包含整数,或者不可迭代的东西:
kvp2 = [0, 42]
mydict.update(kvp2)
You'd get this error你会得到这个错误
TypeError: cannot convert dictionary update sequence element #0 to a sequence
类型错误:无法将字典更新序列元素 #0 转换为序列
So, to update the dict with the result of a split()
operation, you simply need to wrap that list in another iterable (a list in the following example).因此,要使用
split()
操作的结果更新 dict,您只需将该列表包装在另一个可迭代对象(以下示例中的列表)中。
mystring = "test2=42"
mydict.update([mystring.split("=")])
Now if you wanted that iterable to be a tuple, there's a small gotcha.现在,如果您希望该可迭代对象成为元组,则有一个小问题。 Just wrapping
mystring.split()
in parentheses like so: (mystring.split("="))
won't create the tuple.只需将
mystring.split()
包裹在括号中,如下所示: (mystring.split("="))
不会创建元组。 Instead, you need to add the comma (mystring.split("="), )
to get it to create a tuple.相反,您需要添加逗号
(mystring.split("="), )
以使其创建一个元组。
t1 = (mystring.split("="))
print(type(t1))
# Output: list
t2 = (mystring.split("="), )
print(type(t2))
# Output: tuple
mydict.update((mystring.split("="), ))
If you had a list of N
strings that alternated between keys and values, it'd be fairly easy to reshape it into a N/2 x 2
list of key-value pairs:如果您有一个在键和值之间交替的
N
字符串的列表,那么将其重塑为N/2 x 2
键值对列表将相当容易:
mydict = {"test": "1"}
all_kvp = ["key1", "val1", "key2", "val2", "key3", "val3"]
kvp = [(k, v) for k, v in zip(all_kvp[::2], all_kvp[1::2])] # creates a list-of-tuples, but a list-of-lists would also work.
mydict.update(kvp)
# mydict: {'test': '1', 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
From documentation :从文档:
update()
accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two).update()
接受另一个字典对象或键/值对的可迭代对象(作为元组或其他长度为 2 的可迭代对象)。
In case of your code there was an exception because "test2"
is an iterable but of length 5 rather than 2.如果你的代码有一个例外,因为
"test2"
是一个可迭代的但长度为 5 而不是 2。
You could eg wrap your list of 2 into another list to make it work:您可以例如将您的 2 列表包装到另一个列表中以使其工作:
>>> mydict = {"test": "1"}
... key_value_pair = ["test2", "42"]
... mydict.update([key_value_pair])
>>> mydict
{'test': '1', 'test2': '42'}
but the idea is to split a string and use the two elements directly as key/value pair:
但想法是拆分一个字符串并直接使用两个元素作为键/值对:
If you want to split the string and use the two elements directly as key/value pair, then I think this is the simplest way to go:如果要拆分字符串并直接使用两个元素作为键/值对,那么我认为这是最简单的方法:
mydict = {"test": "1"}
mydict.update(["test2=42".split("=")]) # this statement
print(mydict)
This prints as expected:这按预期打印:
{'test': '1', 'test2': '42'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.