Home > Back-end >  How to get key value by another key value of dict
How to get key value by another key value of dict

Time:11-16

I am trying to get hero name by hero id for my program.

Let's assume that I have an array with hero ids: hero_ids = [1, 15, 27, 44, 135]

and a dict with a list of dicts with hero information:

{
    "heroes": [
        {
            "name": "hero1",
            "id": 1,
        },
        {
            "name": "hero2",
            "id": 2,
        },
        {
            "name": "hero3",
            "id": 3,
        },

Question: how do I get a list of hero names for each hero id?

I've spent 3 hours on this but don't understand the idea. I've tried list comprehensions (seems they can't be used with dicts), manual indexing going through hero_ids array or heroes array but no luck

CodePudding user response:

You can use list comprehension -

data = {
    "heroes": [
        {
            "name": "hero1",
            "id": 1,
        },
        {
            "name": "hero2",
            "id": 2,
        },
        {
            "name": "hero3",
            "id": 3,
        }]
}
hero_ids = [1, 2, 3]
hero_names = [info.get('name') for info in data['heroes'] for hero_id in hero_ids if info.get('id') == hero_id]
print(hero_names)

Output:

['hero1', 'hero2', 'hero3']

Note that this will be a bit slower, in case the list of heroes is huge, so might be a good idea to convert your input into a dict.


A better way might be create a dict with key being hero_id and value being hero_name -

# convert data into a dict format
hero_map = {x.get('id'): x.get('name') for x in data['heroes']}
hero_ids = [1, 2, 3]
hero_names = [hero_map[i] for i in hero_ids]
print(hero_names)

Output:

['hero1', 'hero2', 'hero3']

CodePudding user response:

An even shorter way than the one proposed is to use the in keyword, that allows you to check if an instance is contained in a set of others.

Using this avoids nested loops.

data = {
    "heroes": [
        {"name": "hero1", "id": 1},
        {"name": "hero2", "id": 2},
        ...
    ]
}

hero_ids = [1, 2, 3]
matching_names = [hero.get('name') for hero in data.get('heroes') if hero.get('id') in hero_ids]

print(matching_names)
  • Related