How to generate different values for same key in dictionaries?

I'm a newbie and can't for the life of me figure this out! Trying to get a python dictionary with the following structure, a list of dictionaries:

json_data = [ {"id": 1,"name": "Meghan"},
        {"id": 2,"name": "Julia"},
        {"id": 3,"name": "Kevin"}
        ]

I need the same keys in each of the dictionaries and the id's have to be from values 1 to 100. I'd like to dynamically populate this if possible.

Here's what I've tried so far:

json_data = {}
for i in range(1, 11):
    if i not in json_data:
        json_data['id'] = i

But as you can see, the id keeps getting overwritten and produces a file like so:

{
    "id": 10
}

Any help in the right direction would be great!

4 answers

  • answered 2019-07-10 22:09 R10t--

    I'm not sure what you're asking.

    If it is about adding ID's to an existing list without duplicating an id:

    JSON does not preserve it's order so the only way to do this is first loop through your list, find the greatest id that currently exists, and then begin counting from there. If you know elements will never bet deleted from your list you can just use the length of the list as your start index. Alternatively you could use a GUID which has an extremely low probability of being duplicated.

    If it is about items not being appended to your list:

    Change the declaration of json_data to: json_data = [] then use json_data += [{'id': i}]

  • answered 2019-07-10 22:09 Smuuf

    Do you mean something like this?

    json_data = []
    for i in range(1, 11):
        json_data.append({'id': i})
    

    Resulting in:

    [{'id': 1},
     {'id': 2},
     {'id': 3},
     {'id': 4},
     {'id': 5},
     {'id': 6},
     {'id': 7},
     {'id': 8},
     {'id': 9},
     {'id': 10}]
    

  • answered 2019-07-10 22:12 Sean Tashlik

    I think your problem may be that you forgot to put it inside a list:

        json_data = [{"id": i} for i in range(1, 11)]
    

  • answered 2019-07-10 22:39 tarheel

    There are two mis-steps in the current code:

    1. The if i not in json_data line is only looking at the elements of the list, not the value of the id key inside the dictionary.
    2. The json_data['id'] = i line is over-writing the list of dictionaries, with a dictionary under the same variable name of json_data.

    The below code will address both of those mis-steps.

    json_data = [ {"id": 1,"name": "Meghan"},
            {"id": 2,"name": "Julia"},
            {"id": 3,"name": "Kevin"}
            ]
    
    for i in range(1, 11):
      if i not in [d['id'] for d in json_data]:
        json_data.append({"id": i})
    

    If you were to print the json_data list after running the code above, it would output the following:

    [{'id': 1, 'name': 'Meghan'}, {'id': 2, 'name': 'Julia'}, {'id': 3, 'name': 'Kevin'}, {'id': 4}, {'id': 5}, {'id': 6}, {'id': 7}, {'id': 8}, {'id': 9}, {'id': 10}]