dyao
dyao

Reputation: 1011

Tuple with nested list into dictionary

Suppose I have this tuple:

k=('a', ['email1', 'email2']), ('b',['email3'])

When I do this:

j=dict(k)

it should return this according to python documentation:

{'a': ['email1', 'email2'], 'b': ['email3']}

This is easy enough when the tuple is in key, value pairs. But what if instead it was just one tuple? (example below):

   k=('a', ['email1', 'email2'], 'b',['email3'])

I tried to do:

dict((k,))

But it doesn't work if there is more than one element in the tuple.

EDIT

  1. Is there a way to do this?
  2. Whats the difference between dict((k,)) and dict[k]? They seem to give the same output.

Upvotes: 0

Views: 75

Answers (4)

mission.liao
mission.liao

Reputation: 338

You can init a dict with a list of pairs(length 2 tuples), that's why it works in this case:

k=('a', ['email1', 'email2']), ('b',['email3'])
dict(k)     # key: a, b
            # value: ['email1', 'email2'], ['email3']

The constructor of dict would take the first element in each tuple as key, and the second one as value.

In this second case, what you pass is one tuple with four elements, there is no heuristic for dict to distinguish 'key' and 'value'. Therefore, you need to follow @Kit Sunde's answer to split your tuples.

Upvotes: 1

Kit Sunde
Kit Sunde

Reputation: 37095

This is effectively the same problem as How do you split a list into evenly sized chunks in Python? except you want to group it to 2. I.e. given:

def chunk(input, size):
    return map(None, *([iter(input)] * size))

You would do:

 k=('a', ['email1', 'email2'], 'b',['email3'])
 dict(chunk(k, 2))

Output:

{'a': ['email1', 'email2'], 'b': ['email3']}

For your additional questions, are you using python3? dict[k] may hit __getitem__, but I'm not familiar with python3. dict((k,)) is hitting the constructor. In python2.7 they are definitely not equivalent:

>>> dict((k,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 4; 2 is required
>>> dict[k]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object has no attribute '__getitem__'

Upvotes: 2

Geeocode
Geeocode

Reputation: 5797

You can do as follows:

k=('a', ['email1', 'email2'], 'b',['email3'])
l = [(k[i], k[i+1]) for i in range(0, len(k), 2)]
l = dict(l)

print l

Output:

{'a': ['email1', 'email2'], 'b': ['email3']}

Upvotes: 1

NuclearPeon
NuclearPeon

Reputation: 6059

You cannot have lists as dictionary keys. Dictionary keys can be immutable types, see https://docs.python.org/2/tutorial/datastructures.html#dictionaries

By having a tuple with lists as some of the keys as your example shows, it will fail.

Also, your tuple example only works when the tuple has two elements, so one can become the key and the other the value. I used this example:

k=('a', ['email1', 'email2']), ('b',['email3']), ('c',['email4'], 'a')

and because the last tuple has 3 items, it will fail. Your second example was one tuple of more than 2 elements, so it cannot be converted.

I feel you are trying to extend the dict function past what it is meant to do, if you want to custom build dictionaries, look up the dict function, look up dictionary comprehensions, or use for loops to add in elements.

http://legacy.python.org/dev/peps/pep-0274/ <-- dictionary comprehensions

It's not too clear what you are trying to do, aside from easy tuple-to-dict conversions.

Upvotes: 1

Related Questions