Hannan
Hannan

Reputation: 1191

zipping two differently sized lists to make dictionaries

I have the following two differently sized lists and want to combine them to a dictionary using zip() function.

stocks = ['CAT', 'IBM', 'MSFT']
prices = [20, 30, 40, 21, 31, 41, 22, 32, 42, 23, 33, 43]

Here is what I'm trying to do:

from itertools import cycle
ziplist = []
ziplist.append(dict(zip(cycle(stocks), prices)))

I'm getting output as:

[{'CAT': 23, 'IBM': 33, 'MSFT': 43}]

My expected output should be a list with multiple dicts:

[{'CAT': 20, 'IBM': 30, 'MSFT': 40}, {'CAT': 21, 'IBM': 31, 'MSFT': 41}, {'CAT': 22, 'IBM': 32, 'MSFT': 42}, {'CAT': 23, 'IBM': 33, 'MSFT': 43}]

Upvotes: 2

Views: 49

Answers (3)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

create an iterator out of prices, then build the sub-dirs the proper number of times, picking a value at a time with next:

stocks = ['CAT', 'IBM', 'MSFT']
prices = [20, 30, 40, 21, 31, 41, 22, 32, 42, 23, 33, 43]

price_iter = iter(prices)

result = [{x:next(price_iter,0) for x in stocks} for _ in range(len(prices)//len(stocks)) ]

(in that case, if prices is too short, next yields 0 as a default value thanks to the second argument)

Upvotes: 2

Stephen Rauch
Stephen Rauch

Reputation: 49784

Using cycle will not allow you to see the divisions. Instead loop the calculable length. You can use an iterator to keep track of where you are in the price list:

Code:

prices_iter = iter(prices)
data = [dict(zip(stocks, prices_iter)) for i in range(len(prices) // len(stocks))]

Test Code:

stocks = ['CAT', 'IBM', 'MSFT']
prices = [20, 30, 40, 21, 31, 41, 22, 32, 42, 23, 33, 43]

prices_iter = iter(prices)
data = [dict(zip(stocks, prices_iter)) for i in range(len(prices) // len(stocks))]

print(data)

Results:

[
    {'IBM': 30, 'MSFT': 40, 'CAT': 20}, 
    {'IBM': 31, 'MSFT': 41, 'CAT': 21}, 
    {'IBM': 32, 'MSFT': 42, 'CAT': 22}, 
    {'IBM': 33, 'MSFT': 43, 'CAT': 23}
]

Upvotes: 3

Javier
Javier

Reputation: 420

Maybe this?

stocks = ['CAT', 'IBM', 'MSFT']
prices = [20, 30, 40, 21, 31, 41, 22, 32, 42, 23, 33, 43]

[dict(zip(stocks,prices[i:i+len(stocks)])) for i in range(0,len(prices),len(stocks))]

Upvotes: 2

Related Questions