英文:
Need help in accessing dictionary values in list
问题
我正在尝试访问包含字典的列表中的值,需要将key
和value
作为字符串传递。
例如:我有一个字典列表 -
details = [{'name': 'veeresh', 'href': 'www.google.com', 'id': '12345'}, {'name': 'Chandan', 'href': 'www.facebook.com', 'id': '67895'}]
我想根据我传递的name
来访问href
属性。
如果我尝试如下 -
details['name']['href']
我会收到一个错误消息 -
TypeError: list indices must be integers or slices, not str
是否有其他方法可以访问它?
英文:
I am trying to access the values in list of dictionary where I need to pass key
and value
as string
ex: I have list of dictionary -
details = [{'name': 'veeresh', 'href': 'www.google.com', 'id': '12345'}, {'name': 'Chandan', 'href': 'www.facebook.com', 'id': '67895'}]
I want to access href
attribute based on name I pass
If I try below -
details['name']['href']
I am getting an error -
> TypeError: list indices must be integers or slices, not str
Is there any other way to access it?
答案1
得分: 1
A list's items can only be accessed sequentially or by index (positions). you would either have to perform a sequential search or build a dictionary of dictionaries with the name as its key.
For example:
details = [{'name': 'veeresh', 'href': 'www.google.com', 'id': '12345'},
{'name': 'Chandan', 'href': 'www.facebook.com', 'id': '67895'}]
nameDetails = {d['name']: d for d in details}
nameDetails['veeresh']['href'] # 'www.google.com'
英文:
A list's items can only be accessed sequentially or by index (positions). you would either have to perform a sequential search or build a dictionary of dictionaries with the name as its key.
For example:
details = [{'name': 'veeresh', 'href': 'www.google.com', 'id': '12345'},
{'name': 'Chandan', 'href': 'www.facebook.com', 'id': '67895'}]
nameDetails = { d['name']:d for d in details }
nameDetails['veeresh']['href'] # 'www.google.com'
答案2
得分: 0
你可以使用一个for循环来检查你传递的name
,并返回相应的href
属性 -
def get_href(details, name):
for values in details:
if values['name'] == name:
return values['href']
href_val = get_href(details, 'veeresh')
英文:
You can use a for loop to check for the name
you passed and return the respective href
attribute -
def get_href(details, name):
for values in details:
if values['name'] == name:
return values['href']
href_val = get_href(details, 'veeresh')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论