如果给出了 id,我如何在这个列表中找到其他属性的其他值,里面有字典

if id is given, how do i find the other values of other attributes in this list with dictionaries inside

my_playlists=[
    {"id":1,"name":"Bicycle Playlist","numberOfSongs":3},
    {"id":2,"name":"Coding Playlist","numberOfSongs":2}
]

如果输入是1,应该被认为是一个id。我如何获得名称属性?及其价值?

使用列表理解作为:

my_playlists=[
    {"id":1,"name":"Bicycle Playlist","numberOfSongs":3},
    {"id":2,"name":"Coding Playlist","numberOfSongs":2}
]

inp_id = 1
res = [elt['name'] for elt in my_playlists if elt['id'] == inp_id][0]
print(res)

输出:

Bicycle Playlist

试试这个

>>> my_playlists=[
...     {"id":1,"name":"Bicycle Playlist","numberOfSongs":3},
...     {"id":2,"name":"Coding Playlist","numberOfSongs":2}
... ]
>>> 
>>> next(item for item in my_playlists if item["id"] == 1).get('name')
'Bicycle Playlist'
>>> 

使用 for 循环

for i in my_playlists:         
    if i.get('id') == 1:       
        print(i.get('name'))   

try this:

my_playlists=[
{"id":1,"name":"Bicycle Playlist","numberOfSongs":3},
{"id":2,"name":"Coding Playlist","numberOfSongs":2}
]
Id = 1
for j in my_playlists:
    if j.get('id') == Id:
        print(j.get('name'))