Find Element by Dictionary-ID in Python List[Dict]

Viewed 2075

The problem I got, is the following: I got JSON-Data which I already converted to a dictionary. The JSON-Data looks like this:

[{"text": "foo1", "value": 1},
{"text": "foo2", "value": 2}]

So my converted json in Python is json = [{'text': 'foo1', 'value': 1}, {'text': 'foo2', 'value': 2}].

The text in these dictionaries is random data and can be swapped for anything the value on the other hand can be interpreted as a fix and unique ID from 1 to infinity.

Now my question is what would possible be the most efficient way of getting out the text.

Because what I tried was

foo1 = [v['text'] for v in json if json['value'] == 1][0]    # and
foo2 = {list(v.values())[1]: list(v.values())[0] for v in json}[2]

though I have to admit that I am not really happy with these solutions...

2 Answers

I would recommend Błotosmętek's answer if you need to do multiple lookups, however if you just need a single value, I would recommend:

def lookup(value):
    return next(v['text'] for v in json if v['value'] == value)

This is similar to the code you gave, but the big difference is that it does not have to search the entire list even after it has found the value, because it uses a generator rather than list comprehension.

The most efficient way, if you need to get several items by value, is to convert this list of dicts into a dict with value as keys and text as values:

d = { x['value']: x['text'] for x in dic }

Now you can just use d[n] to find text for value equal n.

Related