14

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?

2
  • Give us an example of your input, and explain what you expect to happen. Commented May 8, 2011 at 18:35
  • You might want to use set instead of dict. Commented May 8, 2011 at 18:48

3 Answers 3

21

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}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.