backofsky
backofsky

Reputation: 41

Python list of dictionaries from two lists

I have tried to create list of dictionary.

In order to map two lists in list of dictionaries. Where:

k = ['00-00', '00-01', '00-02', '00-00', '00-01', '00-02']
a = [1.08, 2.89, 3.88, 4.44, 8.88, 9.99]

The list of dictionaries must equal:

[{'00-00':1.08, '00-01':2.89, '00-02':3.88}, {'00-00':4.44, '00-01':8.88, '00-02':9.99}]

My code:

res = []
for item in range(0, len(a)):
     res.append(dict(zip(k, a[item: len(a)])))

However it doesn't work so well

Output:

[{'00-00': 4.44, '00-01': 8.88, '00-02': 9.99}, {'00-00': 8.88, '00-01': 9.99, '00-02': 4.44}, {'00-00': 9.99, '00-01': 4.44, '00-02': 8.88}, {'00-00': 4.44, '00-01': 8.88, '00-02': 9.99}, {'00-00': 8.88, '00-01': 9.99}, {'00-00': 9.99}]

Thank you for answering my question.

Upvotes: 0

Views: 56

Answers (1)

Mouad Slimane
Mouad Slimane

Reputation: 1065

try:

[dict(zip(k,a[0:3])),dict(zip(k,a[3:]))]

Upvotes: 1

Related Questions