Python dictionary filter certain part

Question:

i’m new to python and i got a problem with dictionary filter.
I searched a really long time for solution and asked on several discord server, but no one could really help me.

If i have a dictionary like this:

[
    {"champion": "ahri", "kills": 12, "assists": 7, "deaths": 4, "puuid": "17hd72he7wu"}
    {"champion": "sett", "kills": 14, "assists": 5, "deaths": 7, "puuid": "2123r3ze7wu"}
    {"champion": "thresh", "kills": 9, "assists": 16, "deaths": 2, "puuid": "32d72h5t5gu"}
]

How do i filter out only 1 certain part by puuid(value)? So it looks like this:

puuid = "32d72h5t5gu"

[
    {"champion": "thresh", "kills": 9, "assists": 16, "deaths": 2, "puuid": "32d72h5t5gu"}
]

with all other parts of dictionary removed.

Asked By: Frodox

||

Answers:

use a list comprehension and cycle through the dictionaries in your list to only keep the one that meets the specified conditions.

[
{"champion": ahri, "kills": 12, "assists": 7, "deaths": 4, "puuid": 17hd72he7wu}
{"champion": sett, "kills": 14, "assists": 5, "deaths": 7, "puuid": 2123r3ze7wu}
{"champion": thresh, "kills": 9, "assists": 16, "deaths": 2, "puuid": 32d72h5t5gu}
]
newlist = [i for i in oldlist if (i['puuid'] == '32d72h5t5gu')]
Answered By: Michal Borwoski

you want something like this:

new_list = [ x for x in orgininal_list if x[puuid] == value ]

its called a list comprehension

Answered By: LhasaDad

As the first thing, you should search for a question similar to yours.

This gives you half of the answer you’re looking for: you can use a list comprehension.

dictionaries_list = [
    {"champion": "ahri", "kills": 12, "assists": 7, "deaths": 4, "puuid": "17hd72he7wu"}
    {"champion": "sett", "kills": 14, "assists": 5, "deaths": 7, "puuid": "2123r3ze7wu"}
    {"champion": "thresh", "kills": 9, "assists": 16, "deaths": 2, "puuid": "32d72h5t5gu"}
]

result = [d for d in dictionaries_list if d["puuid"] == "32d72h5t5gu"]
Answered By: FLAK-ZOSO
dictionary = [
    {"champion": "ahri", "kills": 12, "assists": 7,
        "deaths": 4, "puuid": "17hd72he7wu"},
    {"champion": "sett", "kills": 14, "assists": 5,
        "deaths": 7, "puuid": "2123r3ze7wu"},
    {"champion": "thresh", "kills": 9, "assists": 16,
        "deaths": 2, "puuid": "32d72h5t5gu"}
]

new_list = [i for i in dictionary if (i['puuid'] == '32d72h5t5gu')]

list Comprehension

Answered By: Asher
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.