ElisaFo
ElisaFo

Reputation: 140

efficiently compare the dictionary values with list items

I have a dictionary, which I need to compare its values after iteration with a list.

this is my code:

mdic = json.loads(data)
mylist = ['blue', 'green', 'red', 'black']
if not mdic['color_detail']:
   raise ValueError('No color_detail available')

color_registered = False
for e in mylist:
    if dic['color_detail'] == e:
           color_registered = True
if not color_registered:
   raise ValueError('Color not registered')

Is there a better way to write my code? (I mean a way to skip the False/True flags)

Upvotes: 0

Views: 78

Answers (4)

el_oso
el_oso

Reputation: 1061

Why use a list when you can use a set?

mdic = json.loads(data)

myset = {'blue', 'green', 'red', 'black'}

if mdic['color_detail'] in myset:
    print('good selection')
else:
    print('bad selection')

you can use the keyword in with any sequence, eg lists, tuples, strings, sets. the benefit of sets is one lookup is performed, whereas in a list each item is checked in turn until the item is found. In the worst case the item is located at the end of the list and for long lists this adds up.

Upvotes: 0

Manuel
Manuel

Reputation: 910

The second block ought to be just this:

if dic['color_detail'] not in mylist:
   raise ValueError('Color not registered')

And the first check might better also cover the non-existence in mdic rather than assuming it's always there:

if not mdic.get('color_detail'):
   raise ValueError('No color_detail available')

Upvotes: 1

Vijay L
Vijay L

Reputation: 1

you want to loop the dict values eg:

for i,j in dict.items():
    if j in list:
        #your logic
    else:
        #your logic

Upvotes: 0

a_guest
a_guest

Reputation: 36249

You can use the builtin any function:

color_registered = any(e == dic['color_detail'] for e in mylist)

Upvotes: 4

Related Questions