Aztec-3x5
Aztec-3x5

Reputation: 155

Check if list as value(with atleast one element) exists in dictionary and return it

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.

Upvotes: 0

Views: 36

Answers (3)

not_speshal
not_speshal

Reputation: 23146

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"]]

Upvotes: 1

Tranbi
Tranbi

Reputation: 12701

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()]

Upvotes: 2

defladamouse
defladamouse

Reputation: 625

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)

Upvotes: 1

Related Questions