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?
With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.
Python dict() Function The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.
Python Dictionary get() Method The get() method returns the value of the item with the specified key.
Space-time tradeoff The fastest way to repeatedly lookup data with millions of entries in Python is using dictionaries. Because dictionaries are the built-in mapping type in Python thereby they are highly optimized.
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With