Convert a list of tuples to dictionary
Asked Answered
I

3

6

I have a list of tuples that I would like to convert to a dictionary. Each of the tuples in the list has four elements:

N = [('WA', 'OR', 'CA', 'HI'), ('MA', 'NY', 'PA', 'FL')]

How do I get a dictionary set up where the first element of the tuple is the key, and the value is a tuple of the rest of the elements?

dict = {"WA": ("OR", "CA", "HI"), "MA": ("NY", "PA", "FL")}

I tried something along the lines of this, but I am getting a truncated version of the fourth element (at least that what it looks like to me, my actual list is much larger than the example list):

for i in range(len(N))}:
    for v in N[i]:
        dict[i] = v[1:4]
Incisive answered 10/8, 2020 at 18:14 Comment(0)
S
12

Think about it inside out. Given a single tuple, how do you make a key value pair?

tup[0]: tup[1:]

Now just wrap this in the dictionary:

d = {tup[0]: tup[1:] for tup in N}
Stigmasterol answered 10/8, 2020 at 18:19 Comment(0)
P
3

In your code v[1:4] is already each element of the tuple. That is why the first character is ignored.

You don't need a nested loop.

You can use a dict comprehension (obviously use better variable names):

N = [('WA', 'OR', 'CA', 'HI'), ('MA', 'NY', 'PA', 'FL')]
d = {t[0]: t[1:] for t in N}
print(d)

outputs

{'WA': ('OR', 'CA', 'HI'), 'MA': ('NY', 'PA', 'FL')}

You could also use dict directly. It accepts an iterable of tuples where the first element will be the key and the second element will be the value.

d = dict((t[0], t[1:]) for t in N)
Plowshare answered 10/8, 2020 at 18:18 Comment(0)
S
2

Try this

>>> N = [('WA', 'OR', 'CA', 'HI'), ('MA', 'NY', 'PA', 'FL')]
>> d = {key: (*values,) for key, *values in N}
>>> d
{'WA': ('OR', 'CA', 'HI'), 'MA': ('NY', 'PA', 'FL')}

for key, *values in N means that it will take the first element of each tuple as key, and it will put the remaining elements in values.

Slave answered 10/8, 2020 at 18:17 Comment(3)
Or {key: (*values,) for key, *values in N} but yours is explicit, so that's better.Florina
This seems to be doing tons of extra unnecessary work (unpacking and repacking the tuple)Plowshare
@DeepSpace, the user is not stating "without doing extra unnecessary work", he is just asking for a solution. I focused on readability, but thanks for mentioning in case that matters more for him.Slave

© 2022 - 2024 — McMap. All rights reserved.