Home > Enterprise >  create a list from dictionary based on a specific Key
create a list from dictionary based on a specific Key

Time:12-20

If you have a list of dictionaries:

How to do you filter the names of all the female or male in a list?

I was trying as below

example = [
{'name':'Jane','gender':'female'},
{'name':'Ben','gender':'male'},
{'name':'Kate','gender':'female'},
{'name':'James','gender':'male'},
{'name':'Lilly','gender':'female'},
{'name':'Sam','gender':'male'},
{'name':'Grace','gender':'female'},
{'name':'Dan','gender':'male'}
]

for dictionary in example:
    dictfilt = lambda x, y: dict([(i, x[i]) for i in x if i in set(y)])
    wanted_keys = ("name", "gender")
    result = dictfilt(dictionary, wanted_keys)
    print(result)

#### The output will give a tuple of the name and the gender ####

for item in result.items():
    print(item)
    for key, value in result.items():
        if value == 'one_day':
            print(key)

but it is far from what I am looking for.

CodePudding user response:

If you want to filter the list of dictionaries you can use a list-comprehension:

example = [
    {"name": "Jane", "gender": "female"},
    {"name": "Ben", "gender": "male"},
    {"name": "Kate", "gender": "female"},
    {"name": "James", "gender": "male"},
    {"name": "Lilly", "gender": "female"},
    {"name": "Sam", "gender": "male"},
    {"name": "Grace", "gender": "female"},
    {"name": "Dan", "gender": "male"},
]

females = [d["name"] for d in example if d["gender"] == "female"]
males = [d["name"] for d in example if d["gender"] == "male"]

print(f"{females=}")
print(f"{males=}")

Prints:

females=['Jane', 'Kate', 'Lilly', 'Grace']
males=['Ben', 'James', 'Sam', 'Dan']

CodePudding user response:

Hope this works for you:

my_list = [
    {"name": "Jane", "gender": "female"},
    {"name": "Ben", "gender": "male"},
    {"name": "Kate", "gender": "female"},
    {"name": "James", "gender": "male"},
    {"name": "Lilly", "gender": "female"},
    {"name": "Sam", "gender": "male"},
    {"name": "Grace", "gender": "female"},
    {"name": "Dan", "gender": "male"},
]
m=[]
f=[]
for i in my_list:
    if i["gender"]=="male":
        m.append(i["name"])
    else:
        f.append(i["name"])
print(f"Male:\n{m}\nFemale:\n{f}")

New code:

my_list =[{'id': '*1', 'name': 'admin', 'password': '1234', 'profile': 'default', 'uptime': '1h3m49s', 'bytes-in': '769490', 'bytes-out': '9543516', 'packets-in': '4389', 'packets-out': '7383', 'dynamic': 'false', 'disabled': 'false'}, {'id': '*2', 'server': 'hotspot1', 'name': 'ARTRbD0W', 'password': 'ARTRbD0W', 'profile': '1hour', 'limit-uptime': '1h', 'uptime': '0s', 'bytes-in': '0', 'bytes-out': '0', 'packets-in': '0', 'packets-out': '0', 'dynamic': 'false', 'disabled': 'false', 'comment': '1 Hour : "30"'}]
names=[]
for i in my_list:
    if i["profile"]=="1hour":
        names.append(i["name"])
print(f"Names:\n{names}")

Result:

Names:
['ARTRbD0W']

Screenshot

  • Related