Home > front end >  Search in List of dict Python
Search in List of dict Python

Time:11-04

I have a list with some dicts inside. The list looks like this:

files = [
{'name': "text.txt", 'size': 10, 'location': "cloud", 'info': "Nothing"},
{'name': "img.jpg", 'size': 200, 'location': "local", 'info': "private"},
{'name': "cars.txt", 'size': 109, 'location': "cloud", 'info': "private"}
]

I also have a folder where "text.txt", "img.jpg" and "cars.txt" are located. Somehow I have to get all elements where "location" is "cloud" AND "info" is "Nothing".

The only way to sort the data is by using the "next" function

next((item for item in files if item["location"] == "cloud"), None)

What is the fastest way to achieve this? And also to sort by "location" and "info"?

CodePudding user response:

One of the way will be this

list(filter(lambda x: x["location"]=="cloud" and x["info"]=="Nothing",files))
# [{'name': 'text.txt', 'size': 10, 'location': 'cloud', 'info': 'Nothing'}]

If you just want the names:

list(map(lambda x: x["name"], filter(lambda x: x["location"]=="cloud" and x["info"]=="Nothing",files)))
# ['text.txt']

CodePudding user response:

Using list comprehension, Just iterate throught the dictionaries and get the names.

files = [dic['name'] for dic in files if dic['location'] == 'cloud' and dic['info'] == "Nothing"])
print(files)

Output:

['text.txt']
  • Related