Home > database >  Iterating Through Dictionary with List Values
Iterating Through Dictionary with List Values

Time:07-02

I am looking to iterate through a dictionary and create a new dictionary for each of the values within a list of the value shown below. Each value will be either a single value or a list and each list would have the same length. The first dictionary is the original one, and the others are the first two dictionaries I want to output. I ultimately want to just have those values, do something with them and then move onto the next dictionary output and so on.

dict = {'cost': [1, 3, 4, 8, 10],
        'address': '123 Fake St',
        'phone number': '123-456-7890',
        'item': ['apple', 'banana', 'strawberry', 'paper', 'pencil'],
        'name': 'John David'}

dict1 = {'cost': 1,
         'address': '123 Fake St',
         'phone number': '123-456-7890',
         'item': 'apple',
         'name': 'John David'}

dict2 = {'cost': 3,
         'address': '123 Fake St',
         'phone number': '123-456-7890',
         'item': 'banana',
         'name': 'John David'}

CodePudding user response:

I believe the following comprehension should do the trick:

d = {'cost': [1, 3, 4, 8, 10],
             'address': '123 Fake St',
             'phone number': '123-456-7890',
             'item': ['apple', 'banana', 'strawberry', 'paper', 'pencil'],
             'name': 'John David'}

res = [{**d, "cost": cost, "item": item} for cost, item in zip(d["cost"], d["item"])]

Which yields:

{'cost': 1, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'apple', 'name': 'John David'}
{'cost': 3, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'banana', 'name': 'John David'}
{'cost': 4, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'strawberry', 'name': 'John David'}
{'cost': 8, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'paper', 'name': 'John David'}
{'cost': 10, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'pencil', 'name': 'John David'}

No comp version:

for cost, item in zip(d["cost"], d["item"]):
    modified_d = {**d, "cost": cost, "item": item}
    do_stuff_with_modified_d(modified_d)
  • Related