Home > front end >  python: lookup in a list of dictionaries
python: lookup in a list of dictionaries

Time:10-29

I have a dictionary where the value is a list of dictionaries:

{ 'client1':
   [
     { 'id': 123, 'name': 'test1', 'number': 777 },
     { 'id': 321, 'name': 'test2', 'number': 888 },
     { 'id': 456, 'name': 'test3', 'number': 999 }
   ],
...
}

and there is lots of entries keys by clientX.

Now, in order to fetch entry with e.g. name == test2, I loop through the list and check for name value, something like this:

for l in d['client']:
   if 'test2' in l['name']:
     # process the entry
...

Is there a shorter/compact way to do such a lookup?

CodePudding user response:

You could make use of list comprehension:

if "test2" in [l["name"] for l in d["client"]]:
    # process the entry

This generates the whole list of names for you to compare to, and this does shorten your code by one line while also making it slightly more difficult to read.

CodePudding user response:

i think you want something like this.

for v in d.values():
    item = next((x for x in v if x["name"] == "test2"), None)
    item and print("found: ", item)

and as you are in python2 so instated of item and print("found: ", item)

if item:
    print "found: ", item
  • Related