HPyExc
HPyExc

Reputation: 11

Retrieve only certain keys and values from a dictionary, nested inside a list

I've been stuck on this for hours.. I want to retrieve only ONE individuals keys and values from a dictionary that is nested inside of a list.

GAMERS = [{
        'name': 'Fatboi',
        'parent': 'Dick Van Dyke',
        'game': 'Dark Souls 3',
        'weight': '420 lbs'
    },
    {
        'name': 'Justin',
        'parent': 'Heather Blueberry',
        'game': 'Tetris',
        'weight': '180 lbs'
    },
{
        'name': 'jerkhead',
        'parent': 'none',
        'games': 'Hello Kitty',
        'weight': '240 lbs'
    },{
        'name': 'Tumor',
        'parent': 'Jack Black',
        'games': 'Trying to live',
        'weight': '150 lbs'
    }]

So for instance I want to get Justins information printed only, nobody elses. Any insights?

Upvotes: 1

Views: 40

Answers (2)

Shakeel
Shakeel

Reputation: 2025

You can pass the key which you want and push it to separate list.

GAMERS = [{
        'name': 'Fatboi',
        'parent': 'Dick Van Dyke',
        'game': 'Dark Souls 3',
        'weight': '420 lbs'
    },
    {
        'name': 'Justin',
        'parent': 'Heather Blueberry',
        'game': 'Tetris',
        'weight': '180 lbs'
    },{
        'name': 'jerkhead',
        'parent': 'none',
        'games': 'Hello Kitty',
        'weight': '240 lbs'
    }]


def get_key_pair_list(input_dict, key):
    new_list = []
    for item in input_dict:
        my_dict = {}
        if key in item.keys():
            my_dict[key] = item[key]
            new_list.append(my_dict)

    return new_list

print(get_key_pair_list(GAMERS, 'name'))

Output:

[{'name': 'Fatboi'}, {'name': 'Justin'}, {'name': 'jerkhead'}]

Comprehensive way:

key = 'name'
my_list = [{key, item[key]} for item in GAMERS if key in item.keys() ]
print(my_list)

output:

[{'name', 'Fatboi'}, {'name', 'Justin'}, {'name', 'jerkhead'}]

Upvotes: 1

flakes
flakes

Reputation: 23644

You want to filter the list and grab the first value that matches a predicate. Make sure to handle the case where the item doesnt exist!

filtered_info = (
    item for item in GAMERS if item['name'] == 'Justin'
)

justin_info = next(filtered_info, None)

if justin_info is not None:
    print(justin_info)

Upvotes: 0

Related Questions