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

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

Python: Converting Dictionary With Key Value Pairs That Contain A List of Values into A List of Tuples

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...