Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some problem with dict function

Tags:

python

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?

like image 672
sdsdsdsdas Avatar asked May 08 '11 18:05

sdsdsdsdas


People also ask

Should I use dict () or {}?

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.

What does dict () do in Python?

Python dict() Function The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.

Can you explain the dict get () function?

Python Dictionary get() Method The get() method returns the value of the item with the specified key.

Is Python dict efficient?

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.


2 Answers

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}
like image 98
zeekay Avatar answered Oct 11 '22 23:10

zeekay


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

like image 29
gruntled Avatar answered Oct 11 '22 23:10

gruntled