Tuple to Dict :: TypeError: cannot convert dictionary update sequence element #0 to a sequence

Viewed 2186

This works OK:

In [104]: i = [(1, 'a')]
In [105]: dict(i)
Out[105]: {1: 'a'}

It seems I have a list containing one tuple that I called the dict() function on and it returned a dictionary.

i has not changed due to the call:

In [114]: i
Out[114]: [(1, 'a')]

If I try this:

 In [108]: i = (1, 'a')
 In [109]: dict(i)

I get TypeError: cannot convert dictionary update sequence element #0 to a sequence.

I assume this is because a tuple is immutable. If true, I have not changed anything though, right?

In the working example above i is still just i.

3 Answers

dict() expects you to pass either a mapping object, or an iterable of key-value pairs (each of which must be a 2-element iterable).

A list of 2-tuples is the latter, a single 2-tuple is neither.

dict expects a sequence of sequences, so when you just give it a one dimensional sequence it fails. You can use tuples instead of lists.

d = dict(((1, 1), (2, 2)))

gives us

{1: 1, 2: 2}

From python documentation (link):

class dict(**kwarg)

class dict(mapping, **kwarg)

class dict(iterable,**kwarg)

Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.

If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.

If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.

You are passing a tuple which is an iterable so python is iterating it trying to expand members in 2 (Key and Value) and failing because the members are not a 2 member iterable that can be assigned to Key and value.

Related