2

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

dlmeetei
  • 9,905
  • 3
  • 31
  • 38
smye
  • 79
  • 1
  • 1
  • 10

7 Answers7

8

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.

vielkind
  • 2,840
  • 1
  • 16
  • 16
  • You provided the right answer - but you forgot to loop in - even if it appears dumb, you should add an example of how to loop into your dict to really answers OP – Arount Aug 04 '17 at 12:51
  • Thank you for the help - I decided to go with your solution. @Arount It's okay, I have done it. – smye Aug 04 '17 at 13:03
  • @smye it's also for future users and "teach" to this new fellow what SO expect as a good answer - anyway good you had your answer :) +1 – Arount Aug 04 '17 at 13:16
2

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
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
2

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

Nija I Pillai
  • 1,046
  • 11
  • 13
0

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'}
3kt
  • 2,543
  • 1
  • 17
  • 29
0

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
Krishna
  • 1
  • 1
0

In case someone is actually searching for a solution to properly loop through multiple dicts without creating unnecessary copies or using nested loops...

from itertools import chain

d0 = dict(a=1, b=2)
d1 = dict(c=3, d=4)

for key, val in chain(d0.items(), d1.items()):
   ...
raphael
  • 2,159
  • 17
  • 20
-1

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)
xuhdev
  • 8,018
  • 2
  • 41
  • 69
ankit tyagi
  • 778
  • 2
  • 16
  • 27