[英]Find the value of the defined key of a dict within a list, by matching the dict values
输入的是简单的csv文件,其标题如下所示:
dc,environment,type,component,fqdn,distribution,release
1,prod,web,fo,aa,ubuntu,14.04.5
它由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()
清单包含:
{'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'}
我想获得fqdn
值,当输入将是dc = 1 and component = a
时,例如dc = 1 and component = a
从名为get_foo(dc='1', component='a', environment=None)
和defined def get_foo(**kwargs)
或其他方式。 仅结果是必需的。
因此,这种情况下的预期结果是除3rd之外的所有这些行。
谢谢
更普遍
def get_foo(l, **kwargs):
return [x['fqdn'] for x in l if all(x[i] == kwargs[i] for i in kwargs)]
如果您在字典x
未传递关键字参数,则会抛出KeyError
异常
您的问题表明您有一个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'}]
>>> [x['fqdn'] for x in a if x['dc'] == '1' and x['component'] == 'a']
['aa', 'bb', 'dd']
要将其包装在一个函数中:
def get_foo(dlist, dc='1', component='a'):
return [dv['fqdn'] for dv in dlist
if dv['dc'] == dc
and dv['component'] == component]
接着:
>>> get_foo(a)
['aa', 'bb', 'dd']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.