[英]Find the value of the defined key of a dict within a list, by matching the dict values
Input is simple csv file with header what looks like: 输入的是简单的csv文件,其标题如下所示:
dc,environment,type,component,fqdn,distribution,release
1,prod,web,fo,aa,ubuntu,14.04.5
It is loaded by csv.DictReader(csv)
into the server_list
: 它由
csv.DictReader(csv)
加载到server_list
:
def get_server(**kwargs):
f = open("servers.dat", 'rt')
try:
reader = csv.DictReader(f)
server_list = []
for row in reader:
server_list.append(row)
finally:
f.close()
List contains: 清单包含:
{'component': 'a', 'dc': '1', 'fqdn': 'aa', 'environment': 'prod', 'release': '14.04.5', 'distribution': 'ubuntu', 'type': 'web'}
{'component': 'a', 'dc': '1', 'fqdn': 'bb', 'environment': 'prod', 'release': '14.04.5', 'distribution': 'ubuntu', 'type': 'web'}
{'component': 'b', 'dc': '1', 'fqdn': 'cc', 'environment': 'prod', 'release': '12.04.5', 'distribution': 'ubuntu', 'type': 'web'}
{'component': 'a', 'dc': '1', 'fqdn': 'dd', 'environment': 'test02', 'release': '14.04.5', 'distribution': 'ubuntu', 'type': 'web'}
I would like to get value of fqdn
when input will be eg dc = 1 and component = a
from python function called eg get_foo(dc='1', component='a', environment=None)
and defined def get_foo(**kwargs)
or differently. 我想获得
fqdn
值,当输入将是dc = 1 and component = a
时,例如dc = 1 and component = a
从名为get_foo(dc='1', component='a', environment=None)
和defined def get_foo(**kwargs)
或其他方式。 Only result is required. 仅结果是必需的。
So, expected result in this case are all these lines except 3rd. 因此,这种情况下的预期结果是除3rd之外的所有这些行。
Thank you 谢谢
More generally 更普遍
def get_foo(l, **kwargs):
return [x['fqdn'] for x in l if all(x[i] == kwargs[i] for i in kwargs)]
This will throw a KeyError
exception is you pass a keyword argument not in the dictionary x
如果您在字典
x
未传递关键字参数,则会抛出KeyError
异常
Your question states that you have a list of dict
s, something like this: 您的问题表明您有一个
dict
列表,如下所示:
>>> a = [{'component': 'a',
'dc': '1',
'distribution': 'ubuntu',
'environment': 'prod',
'fqdn': 'aa',
'release': '14.04.5',
'type': 'web'},
{'component': 'a',
'dc': '1',
'distribution': 'ubuntu',
'environment': 'prod',
'fqdn': 'bb',
'release': '14.04.5',
'type': 'web'},
{'component': 'b',
'dc': '1',
'distribution': 'ubuntu',
'environment': 'prod',
'fqdn': 'cc',
'release': '12.04.5',
'type': 'web'},
{'component': 'a',
'dc': '1',
'distribution': 'ubuntu',
'environment': 'test02',
'fqdn': 'dd',
'release': '14.04.5',
'type': 'web'}]
You can always just filter the list of dict
s using list comprehension syntax: 您总是可以使用列表理解语法来过滤
dict
列表 :
>>> [x['fqdn'] for x in a if x['dc'] == '1' and x['component'] == 'a']
['aa', 'bb', 'dd']
To wrap it up in a function: 要将其包装在一个函数中:
def get_foo(dlist, dc='1', component='a'):
return [dv['fqdn'] for dv in dlist
if dv['dc'] == dc
and dv['component'] == component]
And then: 接着:
>>> get_foo(a)
['aa', 'bb', 'dd']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.