user2896120
user2896120

Reputation: 3282

Iterating over lists in dictionary

I have a dictionary that looks like this:

{
   "month": ["January", "February", "March"],
   "volume": [1,2,3],
   "target": [6,8,5]
}

I'd like to loop over each key and value so that I can make a list that looks like this:

["month: January, volume: 1, target: 6", "month: February, volume: 2, target: 8", "month: March, volume: 3, target: 5"]

How do I loop through each key value one by one until I reach the end of the last list's array value? All lists are the same length for each key.

Upvotes: 1

Views: 66

Answers (3)

Diptangsu Goswami
Diptangsu Goswami

Reputation: 5955

d = {
   "month": ["January", "February", "March"],
   "volume": [1,2,3],
   "target": [6,8,5]
}

keys = tuple(d)  # ('month', 'volume', 'target')
values = tuple(zip(*d.values()))  # (('January', 1, 6), ('February', 2, 8), ('March', 3, 5))

your_list = [
    ', '.join(
        f'{keys[i]}: {value[i]}' 
        for i in range(len(keys))  # range(3) in this case
    ) 
    for value in values
]

print(your_list)

Output:

['month: January, volume: 1, target: 6',
 'month: February, volume: 2, target: 8',
 'month: March, volume: 3, target: 5']

Upvotes: 1

Magdrop
Magdrop

Reputation: 578

Using this example:

di = {
   "month": ["January", "February", "March"],
   "volume": [1,2,3],
   "target": [6,8,5],
}

One idea is just to convert it to a list

li = [ [k + ": " +str(v) for v in v_list] for k,v_list in test_dict.items()]

and then do the join using zip

[ ', '.join(l) for l in zip(*li) ]

This is the result:

['month: January, volume: 1, target: 6',
 'month: February, volume: 2, target: 8',
 'month: March, volume: 3, target: 5']

Upvotes: 0

Sabareesh
Sabareesh

Reputation: 751

Assuming all values have same length:

di = {
    "month": ["January", "February", "March"],
    "volume": [1,2,3],
    "target": [6,8,5],
}
sample_length = len(list(di.values())[0])
final_list = []
for j in range(sample_length):
    list_item = []
    for key, val in di.items():
        list_item.append('{}: {}'.format(key, val[j]))
    final_list.append(', '.join(list_item))
print(final_list)

Output:

['month: January, volume: 1, target: 6', 'month: February, volume: 2, target: 8', 'month: March, volume: 3, target: 5']

Upvotes: 0

Related Questions