-1

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?

Mark
  • 6,052
  • 8
  • 61
  • 129
  • 1
    YOu say you want to fetch entry with `name == test2` but in the code you write `'test2' in l['name']` which is a different thing. First is equality, second is inclusion. So what do you really want to fetch? – nadapez Oct 29 '21 at 03:54
  • This expression is the simplest expression for **linear search**. In my suggestion, you can add a break statement at the end of 'if-else clause' to make it run faster – The blank Oct 29 '21 at 03:55
  • Does this answer your question? [Python list of dictionaries search](https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search) – nadapez Oct 29 '21 at 03:57
  • @nadapez, _YOu say you want to fetch entry with name == test2 but in the code you write 'test2' in l['name'] which is a different thing. First is equality, second is inclusion._ I'm newbie in python, thanks for correcting me. `in` returns `True` if a sequence with the specified value is present in object, correct? In my case `l['name']` is a string, so both `==` and `in` would yield `True`. Am I wrong? – Mark Oct 29 '21 at 13:32
  • 1
    `'test2' in l['name']` would also be `true` if `l[name]` is `'test22'` which is incorrect – nadapez Oct 29 '21 at 15:29
  • 1
    @nadapez, I see, that makes a huge difference. So `in` doesn't perform an exact match. – Mark Oct 29 '21 at 15:40

2 Answers2

1

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.

n-l-i
  • 155
  • 6
0

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
Ali Aref
  • 1,893
  • 12
  • 31
  • What is `item and print("found: ", item)` ? – PCM Oct 29 '21 at 04:07
  • it checks if item is not `None` then it prints the value. the `and` looks to the `item` if it was **True** it will go for the other side, if was **Not True** it won't. – Ali Aref Oct 29 '21 at 04:09