Anshul Goyal
Anshul Goyal

Reputation: 139

Check if there are duplicate values in list of dictionaries and update said duplicate values

I have a list of dictionaries that look like this:

[{'id' : '3412' , 'value' : 'x'} , {'id' : '5618' , 'value' : 'y'} , {'id' : '3412' , 'value' : 'z'}]

I need to find out if there are duplicate ids and replace any one of the duplicate id with a randomly generated 4-digit id that does not exist in the list. For example in the above scenario I need to change the id of either the first or third dict so that for example the list may look like:

[{'id' : '3412' , 'value' : 'x'} , {'id' : '5618' , 'value' : 'y'} , {'id' : '6123' , 'value' : 'z'}]

I can find if there are duplicate values in the list using python check if dictionaries value of a key duplicate in list but is there an efficient way to update the dict values?

Upvotes: 0

Views: 674

Answers (2)

Manoj
Manoj

Reputation: 319

Adding to what @Neeraj answered. you can prevent duplicates from reoccuring in random_int() like this.

def random_int(temp):
     val=str(randint(1000, 9999))
     if(val in temp):
         random_int(temp)
     else:
         return val

Upvotes: 1

Neeraj
Neeraj

Reputation: 997

Since you haven't provided any detail on your attempt, here's what I will do at such scenarios:

from random import randint

dict = [{'id': '3412', 'value': 'x'}, {'id': '5618', 'value': 'y'}, {'id': '3412', 'value': 'z'}]


def random_int():
    return str(randint(1000, 9999))

temp = set()
for elem in dict:
    if elem['id'] in temp:
        elem['id'] = random_int()
        temp.add(elem['id'])
    else:
        temp.add(elem['id'])
print(dict)
# [{'id': '3412', 'value': 'x'}, {'id': '5618', 'value': 'y'}, {'id': '1879', 'value': 'z'}]

There's a small probability that randint can generate a number already in the dict, for that you can create another conditional loop if you want.

Upvotes: 1

Related Questions