Best way to loop through multiple dictionaries in Python

Question:

I move dictionary

user = {
    'name': 'Bob',
    'age': '11',
    'place': 'moon',
    'dob': '12/12/12'
}

user1 = {
    'name': 'John',
    'age': '13',
    'place': 'Earth',
    'dob': '12/12/12'
}

What is the best way to loop through each user by adding 1? So the next user would be user2.

Thanks

Asked By: smye

||

Answers:

Instead of assigning user1 as the variable name for the dictionary you could create a new dictionary variable where the key is the user and the value is a nested dictionary with all of the information about the users like this:

users = {
    'user1': {
         'name': 'John',
         'age': '13',
         'place': 'Earth',
         'dob': '12/12/12'
         },
    'user2': {
         'name': 'Bob',
         'age': '11',
         'place': 'moon',
         'dob': '12/12/12'
         }
     ...}

Then you can iterate over the nested dictionary for all users user1, user2,…userN instead of assigning each user to its own variable.

Update:
Here’s how you would then loop across the nested dictionary:

for k, v in users.items():
    print(k, v)

where k is the key (‘user1’, ‘user2’ etc.) and v is the nested dictionary containing the information for the user.

Answered By: vielkind

You can do that, using globals or locals depending on your scope:

>>> for i in range(2):
...     print(globals()['user' + str(i)])
... 
{'name': 'Bob', 'age': '11', 'place': 'moon', 'dob': '12/12/12'}
{'name': 'John', 'age': '13', 'place': 'Earth', 'dob': '12/12/12'}

But as stated in the comments, I would recommend using a list:

>>> users = [user0, user1]
>>> for i in range(2):
...     print(users[i])
... 
{'name': 'Bob', 'age': '11', 'place': 'moon', 'dob': '12/12/12'}
{'name': 'John', 'age': '13', 'place': 'Earth', 'dob': '12/12/12'}
Answered By: 3kt

The easiest way to deal with this (in my opinion is having the dicts in a list.
I’d only use dictionaries if the keys actually mean something. The below is also a valid dict to convert to json.

users = [{
             'name': 'John',
             'age': '13',
             'place': 'Earth',
             'dob': '12/12/12'
             },
            {
             'name': 'Bob',
             'age': '11',
             'place': 'moon',
             'dob': '12/12/12'
             }]

user1 is users[0], user2 is users[1] …

users.append({…}) to add more etc.

And if you loop and want the user number:

for ind,item in enumerate(users):
    print("user{}".format(ind+1))

Prints:

user1
user2
Answered By: Anton vBR

Ideally you should use chainmap to iterate through multiple dictionaries.
import the chainmap from itertools like:

from itertools import Chainmap
d1 = {'k1': 'v1'}
d2 = {'k2': 'v2'}

for k, v in (d1,d2).items():
  print(k,v)
Answered By: ankit tyagi

zip() is the best way to iterate over multiple arrays,list and json objects.
Using zip(), we can iterate over given two json dictionary with a single for loop.

import json
user = {
    'name': 'Bob',
    'age': '11',
    'place': 'moon',
    'dob': '12/12/12'
}

user1 = {
    'name': 'John',
    'age': '13',
    'place': 'Earth',
    'dob': '12/12/12'
}
for (u, u1) in zip(user, user1): 
     print(user[u], user1[u1])

Result

Bob John

11 13

moon Earth

12/12/12 12/12/12

Answered By: Nija I Pillai

here is the code that I did for starting to compare 2 dictionaries.:

    MENU = {
        "espresso": {
            "ingredients": {
                "water": 50,
                "milk": 0,
                "coffee": 18,
            },
            "cost": 1.5,
        },
        "latte": {
            "ingredients": {
                "water": 200,
                "milk": 150,
                "coffee": 24,
            },
            "cost": 2.5,
        },
        "cappuccino": {
            "ingredients": {
                "water": 250,
                "milk": 100,
                "coffee": 24,
            },
            "cost": 3.0,
        }
    }
    resources = {
        "water": 300,
        "milk": 200,
        "coffee": 100,
    }   

    Choice_Ingredients=MENU["ingredients"]

    for (key1, value1), (key2, value2) in zip(Choice_Ingredients.items(), resources.items()):
            
             print (f"{key1} : {value1} n{key2} : {value2}")

The above code prints.:

>water : 200 
>water : 300
>milk : 150 
>milk : 200
>coffee : 24 
>coffee : 100
Answered By: Krishna
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.