1

I am trying to ouptut a list of dicts with unique user IDs. I am using the following code to achieve this:

import json
import random
import string

def random_string_generator(size=15, chars=string.ascii_uppercase + string.digits):
    return '#' + ''.join(random.choice(chars) for _ in range(size))

list_users = ['user_id'] * 5

data = {}
list_json = []
for user in list_users:
    data['user_id'] = random_string_generator() # function to generate a unique key
    list_json.append(data)
print(list_json)

However, my code output is giving the following:

[{'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}]

I would like to know why the list is filled with the same item over and over again?

Y.Henni
  • 165
  • 1
  • 11
  • 1
    Because it *is* the same item; you only ever create one dictionary. – jonrsharpe Jul 14 '18 at 16:36
  • 2
    `data` is a single dictionary, one that you appened to a list multiple times and keep updating. Either create a copy to append to the list, or create a new dictionary each time in the loop, rather than outside of the loop. – Martijn Pieters Jul 14 '18 at 16:40
  • Thanks jonsharpe and Martijn Pieters. Your comments helped me figure out the solution to my problem. Maybe one of you can write down an answer to this so we can close the thread ? – Y.Henni Jul 14 '18 at 16:48

1 Answers1

1

Because you append dict over and over again with the same key user_id.

So you've got list of dictionaries.

Igor S
  • 224
  • 3
  • 11