0

Given the following data structure:

   data = {'NameValues':[
          {'Name':'Field 1', 'Values':['Data 1']}, 
          {'Name':'Field 2', 'Values':['Data 2']}, 
          {'Name':'Field 3', 'Values':['Data 3']}, 
          {'Name':'Field 4', 'Values':['Data 4']}, 
          {'Name':'Field 5', 'Values':['Data 5']}
          ]}

How can find by name and get the value of an element? e.g. get the values for Field 3.

In Ruby I would use this:

p hash['NameValues'].find{ |h| h['Name'] == 'Field 3'}['Values']
#=> ["Data 3"]

This iterates through the NameValues array until a matching element is found. I can then get the Values from the returned element.

Regards

4

4 回答 4

4

对于您的迭代要求,生成器更合适:

>>> data = {'NameValues':[
...           {'Name':'Field 1', 'Values':['Data 1']},
...           {'Name':'Field 2', 'Values':['Data 2']},
...           {'Name':'Field 3', 'Values':['Data 3']},
...           {'Name':'Field 4', 'Values':['Data 4']},
...           {'Name':'Field 5', 'Values':['Data 5']}
...           ]}
>>> i = (v['Values'] for v in data['NameValues'] if v['Name'] == 'Field 3')
>>> next(i)
['Data 3']

StopIteration当没有更多符合您的条件的元素时,您将获得异常。

于 2013-11-04T10:01:50.403 回答
1

您可以使用类似的语法:

p hash['NameValues'].find{ |h| h['Name'] == 'Field 3'}['Values']
#=> ["Data 3"]

filter

>>> data = {'NameValues':[
...           {'Name':'Field 1', 'Values':['Data 1']},
...           {'Name':'Field 2', 'Values':['Data 2']},
...           {'Name':'Field 3', 'Values':['Data 3']},
...           {'Name':'Field 4', 'Values':['Data 4']},
...           {'Name':'Field 5', 'Values':['Data 5']}
...           ]}
>>>
>>> filter(lambda h: h['Name'] == 'Field 3', data['NameValues'])[0]['Values']
['Data 3']
>>>

或者如果你使用 Python 3:

>>> list(filter(lambda h: h['Name'] == 'Field 3', data['NameValues']))[0]['Values']
于 2013-11-04T10:05:35.883 回答
1
for i in data['NameValues']:
    if i['name'] == 'Field 3':
        value = i['values']
# use value here

虽然我是使用 Python 的新手,但可能有人会给出更好的答案。

于 2013-11-04T10:00:15.167 回答
0

f您可以通过以下方式在某个容器C中创建满足您条件的所有值的列表

l = [ e(v) for v in C if f(v) ]

哪里e是一些提取功能。

在您的特定情况下,您可以使用C:=data'NameValues', e(v):=v['values'],f(v):=v['Name']=='Field 3'

l = [ v['Values'] for v in data['NameValues'] if v['Name'] == 'Field 3' ]
print l

如果你只对第一次出现感兴趣

l = [ v['Values'] for v in data['NameValues'] if v['Name'] == 'Field 3' ][0]
print l
于 2013-11-04T10:04:08.937 回答