Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to take a dictionary with key value pairs in which the values are a list and turn them into a list of tuples.

I have a the following dictionary:

d={'a': [33, 21, 4, 32], 'b': [6, 100, 8, 14]}

Desired output:

[(33, 6), (21, 100), (4, 8), (32, 14)]

Below is the code I tried but it does not get me there.

d={'a': [33, 21, 4, 32], 'b': [6, 100, 8, 14]}
  
# Converting into list of tuple 
list = [(key, value) for key, value in d.items()] 
  
# Printing list of tuple 
print(list) 

The code outputs a list value of :

[('a', [33, 21, 4, 32]), ('b', [6, 100, 8, 14])]

What am I doing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can zip the dict values together:

>>> d = {'a': [33, 21, 4, 32], 'b': [6, 100, 8, 14]}
>>> list(zip(*d.values()))
[(33, 6), (21, 100), (4, 8), (32, 14)]

If you only want to get a specific range of values efficiently you could use itertools.islice before consuming it with list.

>>> from itertools import islice
>>> list(islice(zip(*d.values()), 2))
[(33, 6), (21, 100)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...