2

I have list of dictionaries-

[{"id":1,"name":"abc"},{"id":2,"name":"def"},{"id":3,"name":"xyz"}]

I want to get the dictionary where id = 1 and store it in a variable.Something like-

element = {"id":1,"name":"abc"}

I don't want to use for loop to iterate through the list and then fetch the element.

7
  • 4
    First of all, what you have is actually a SyntaxError: there are no commas , between dictionaries. Aside from that there is no other option. Even if you convert the list into some other structure you still need the loop for the conversion.
    – freakish
    Commented May 3, 2016 at 14:10
  • well it is a list. Edited the question to have ,. I was looking for some way using "in" operator or may be some other operator.
    – codec
    Commented May 3, 2016 at 14:13
  • 3
    Why don't you want to loop? Commented May 3, 2016 at 14:13
  • 3
    Convert it to a two dimensional array or pandas dataframe, it will be more easier.
    – xirururu
    Commented May 3, 2016 at 14:17
  • 4
    If the data is in that format, there is literally nothing you can do that does not involve looping. Even if you convert it into some indexed format, that still involves looping in order to do the conversion. Commented May 3, 2016 at 14:17

5 Answers 5

7

No matter what you do, you'll have to iterate over that list.

g = (e for e in elements if e.get('id') == 1)
element = next(g)

The nice thing about this implementation is it only iterates as much as needed to find the next matching element.

1
  • Good one, +1, another nice thing about it, is that you can give next a default value, maybe an empty dictionary: element = next(g, dict())
    – Bahrom
    Commented May 3, 2016 at 14:28
3

The problem you are addressing is called indexing. If you don't know anything about your matching criterias a priori then there is nothing you can do and you have to do the loop. The easiest implementation would be:

my_obj = next(obj for obj in my_list if my_criterium(obj))

where in your case

my_criterium = lambda obj: obj['id'] == 1

However if you know that you will always search by id then you can create an index:

my_index = {obj['id']: obj for obj in my_list}

Then the retrieveing is as simple as

my_obj = my_index[1]

which no longer requires a loop (and thus is fast).

This is under assumption that id is unique on each object (this assumption is not crutial, you can create a different index by storing a list of matched element for each id). The other drawback is that it will be hard to keep both the index and the list consistent between each other.

But no matter what path you chose there is no escape from a loop.

1
Dicts = [{"id":1,"name":"abc"},{"id":2,"name":"def"},{"id":3,"name":"xyz"}]


for d in Dicts:
   if d.get('id') == 1:
      element = d

print element
1

You can store the ids of your dictionary-list into another dictionary using just one for loop. This will be much faster when you have multiple queries.

In [1]: d = [{"id":1,"name":"abc"},{"id":2,"name":"def"},{"id":3,"name":"xyz"}]

In [2]: indices = {v["id"] : index for index, v in enumerate(d)}

In [3]: element = d[indices[1]]

In [4]: print(element)
{'id': 1, 'name': 'abc'}

In [5]: element = d[indices[3]]

In [6]: print(element)
{'id': 3, 'name': 'xyz'}
0

I think I have a solution.

Basically, you convert the list into a string and then you play with it to make a single dictionary. Although, I think that looping over the list is way better.

l = [{"id":1,"name":"abc"},{"id":2,"name":"def"},{"id":3,"name":"xyz"}]
#convert to string
a = str(l) 
#remove parenthesis and curly brackets
a = a.replace('{','').replace('}','').replace('[','').replace(']','').replace(' ','')
#remove 'id' and 'name'
a = a.replace("'id':",'').replace(",'name'",'')
#add curly brackets
a = '{'+a+'}'
#make a dict
exec('a='+a)

>>>a
{1: 'abc', 2: 'def', 3: 'xyz'}

As you can see, you end up with a single dictionary with the right key/value pairs without using a single for loop!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.