I have a following dictionary:
dict1 = {'Diacto Group': {'id': 7547,
'type': 'user',
'name': 'Diacto Group',
'filters': [{'column': 'Core Area',
'values': ['Missiles & Aviation Technology'],
'operator': 'EQUALS',
'not': False}],
'users': [],
'virtualUsers': [],
'groups': [360305499]},
'Diacto People': {'id': 7548,
'type': 'user',
'name': 'Diacto People',
'filters': [{'column': 'Core Area',
'values': ['Aircraft Company', 'Aviation Technology'],
'operator': 'EQUALS',
'not': False}],
'users': [326197441, 1293859642],
'virtualUsers': [],
'groups': []},
}
Basically I want to extract either one of the lists from 'users' or 'groups' if they have list containing atleast one value. I want the final output to look like this:
l1 = [# Extracted list as value from 'group' key from Diacto Group key as users key was blank
# list.
[360305499],
# Extracted list as value from 'users' key from Diacto People key as groups key was
# blank list.
[326197441, 1293859642]
]
List comprehension would be more preferable if possible. Thank you for the efforts and time you put into this.
CodePudding user response:
The simplest I can think of with comprehension, provided either 'users' or 'groups' is not empty:
[v['users'] v['groups'] for v in dict1.values()]
CodePudding user response:
I think it would be possible to do with list comprehension, but extremely difficult to understand.
This would be my approach:
l1 = []
for k in dict1:
if len(dict1[k]['users']) > 0:
l1.append(dict1[k]['users'])
if len(dict1[k]['groups']) > 0:
l1.append(dict1[k]['groups'])
print(l1)
CodePudding user response:
Using list comprehension and filtering out cases where both "users" and "groups" are empty:
l1 = [v["users"] v["groups"] for _, v in dict1.items() if v["users"] v["groups"]]