I want to add the content of a 2-element list to a python dictionary (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
.
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...
From the docs :
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). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: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.
That's why this works:
kvp = ["newkey", "newval"]
mydict.update([kvp])
Each element of the input iterable is a 2-element list.
When you do just
mydict.update(kvp)
update()
tries to ensure that each element of kvp
is a 2-element iterable. 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:
kvp2 = [0, 42]
mydict.update(kvp2)
You'd get this error
TypeError: cannot convert dictionary update sequence element #0 to a sequence
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).
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. Instead, you need to add the comma (mystring.split("="), )
to get it to create a tuple.
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:
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).
In case of your code there was an exception because "test2"
is an iterable but of length 5 rather than 2.
You could eg wrap your list of 2 into another list to make it work:
>>> 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'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.