Reputation: 171
I'm trying to convert a list to a dictionary by using the dict
function.
inpu = input.split(",")
dic = dict(inpu)
The above code is trying to get a string and split
it on ','
and afterwards I use the dict
function to convert the list to a dictionary.
However, I get this error:
ValueError: dictionary update sequence element #0 has length 6; 2 is required
Can anybody help?
Upvotes: 14
Views: 33357
Reputation: 2694
As listed on the Python Data structures Docs. The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples.
so the inpu array must be of form ('key', 'value') at each position, for example
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
your input array is probably greater than 2 in size
Upvotes: 3
Reputation: 1038
A dictionary is a key-value pair which is why it says length-2 lists are needed to match keys to values. You are splitting the input into a flat list, which is why Python is complaining in this case - it doesn't know what to specify as keys and what to specify as values.
Upvotes: 0
Reputation: 53819
dict
expects an iterable of 2-element containers (like a list of tuples). You can't just pass a list of items, it doesn't know what's a key and what's a value.
You are trying to do this:
>>> range(10)
<<< [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> dict(range(10))
---------------------------------------------------------------------------
TypeError: cannot convert dictionary update sequence element #0 to a sequence
dict
expects a list like this:
>>> zip(lowercase[:5], range(5))
<<<
[('a', 0),
('b', 1),
('c', 2),
('d', 3),
('e', 4)]
The first element in the tuple becomes the key, the second becomes the value.
>>> dict(zip(lowercase[:5], range(5)))
<<<
{'a': 0,
'b': 1,
'c': 2,
'd': 3,
'e': 4}
Upvotes: 21