Home > Net >  how to find duplicate values and then print the information about them in dictionary?
how to find duplicate values and then print the information about them in dictionary?

Time:02-02

I want to find duplicate person i.e. 'Tom' and print information about him :

people = {
    '1': {
        'name': ['Tom'],
        'Programs': ['Python  .Java']
    },
    '2': {
        'name': ['Bill'],
        'Programs': ['English, math, science']
    },
    '3': {
        'name': ['Tom'],
        'Programs': ['Python  .Java']
    },
    '4': {
        'name': ['Sam'],
        'Programs': ['English, math, science']
    },
}

CodePudding user response:

used_names = []

for key in people.keys():
    name = people[key]["name"][0]

    if name not in used_names:
        used_names.append(name)
    else:
        print(f'Duplicate person is {key}'   ', '   people[key]["name"][0]   ', '   ' '.join(people[key]["Programs"]))

CodePudding user response:

Similar to the Answer from @Vreny but without the need to access the dictionary's keys:

people = {
    '1': {
        'name': ['Tom'],
        'Programs': ['Python  .Java']
    },
    '2': {
        'name': ['Bill'],
        'Programs': ['English, math, science']
    },
    '3': {
        'name': ['Tom'],
        'Programs': ['Python  .Java']
    },
    '4': {
        'name': ['Sam'],
        'Programs': ['English, math, science']
    }
}

n = []

for v in people.values():
    if (name := v['name'][0]) in n:
        print(f"{name} {repr(*v['Programs'])}")
    else:
        n.append(name)

Output:

Tom 'Python  .Java'
  •  Tags:  
  • Related