Home > Software engineering >  Build new dictionary from what is not in list
Build new dictionary from what is not in list

Time:09-17

I need to compare a list to dictionary values and build a new dictionary with values that don't exist in the old dictionary.

olddict = {'user': ['group1', 'group2'],
        'user2': ['group1']}

RequiredGroups = ['group1', 'group2','group3', 'group4']

newdict= {}
for groups in RequiredGroups:
    for key, value in olddict.items():
        if groups not in value:
            newdict[key] = groups
print(newdict)

current output

{'user2': 'group4', 'user': 'group4'}

desired output

{'user': ['group3', 'group4'],
'user2': ['group2', 'group3', 'group4']}

CodePudding user response:

To modify your solution:

Instead of:

newdict[key] = groups

Use:

newdict.setdefault(key, []).append(groups)

Full code:

olddict = {'user': ['group1', 'group2'],
        'user2': ['group1']}

RequiredGroups = ['group1', 'group2','group3', 'group4']

newdict= {}
for groups in RequiredGroups:
    for key, value in olddict.items():
        if groups not in value:
            newdict.setdefault(key, []).append(groups)
print(newdict)

Output:

{'user2': ['group2', 'group3', 'group4'], 'user': ['group3', 'group4']}

A shorter solution:

It could be much easier with a dictionary comprehension one-liner though:

>>> {k: [x for x in RequiredGroups if x not in v] for k, v in olddict.items()}
{'user': ['group3', 'group4'], 'user2': ['group2', 'group3', 'group4']}
>>> 
  • Related