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")
CodePudding user response:
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']}
CodePudding user response:
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']}