'Function to get details of list of dictionaries

I created a list of dictionaries. Example:

my_list=[
  {
    "id": "first_host",
    "year": 2022,
    "hosts": ["50.60.70.80"]
  },
.....

I am trying to define a function to get these details of the list for each id.

def get_details(details, host_id):
     return config

How do we use it? My expectancy >

get_details(my_list, "first_host")


Solution 1:[1]

The expected return value of get_details() is unclear from the question.

I think this might be the one you are looking for, but not sure because of the ambiguity of the question.

my_list=[{"id": "first_host", "year": 2022, "size": "16g", "hosts": ["50.60.70.80"]},
         {"id": "second_host", "year": 2023, "size": "17g", "hosts": ["60.70.80.90"]},]

def get_details(details, host_id):
    for detail in details:
        if detail["id"] == host_id:
            return detail
get_details(my_list, "first_host")
> {'id': 'first_host', 'year': 2022, 'size': '16g', 'hosts': ['50.60.70.80']}

Solution 2:[2]

You should be able to filter it out -

def get_config(details, host_id):
    req, *_ = filter(lambda entry: entry['id'] == host_id, details)
    return req
print(my_list)
#[{'id': 'first_host', 'year': 2022, 'size': '16g', 'hosts': ['50.60.70.80']},
# {'id': 'second_host', 'year': 2022, 'size': '1g', 'hosts': ['51.60.70.80']}]

print(get_config(my_list, 'first_host'))
# {'id': 'first_host', 'year': 2022, 'size': '16g', 'hosts': ['50.60.70.80']}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 J. Choi
Solution 2 Mortz