需要帮助访问列表中的字典值。

huangapple go评论64阅读模式
英文:

Need help in accessing dictionary values in list

问题

我正在尝试访问包含字典的列表中的值,需要将keyvalue作为字符串传递。

例如:我有一个字典列表 -

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')

huangapple
  • 本文由 发表于 2023年6月5日 01:19:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定