[英]How can I filter a dictionary and store the values in a list?
I want to search for similar values in a dictionary and store the value in a list.我想在字典中搜索相似的值并将值存储在列表中。 This is a little piece of the dictionary Load from yaml:这是从 yaml 加载的字典的一小部分:
global_var:
rt_id: 12345
var_rtr_a:
subnet: 10.10.1.0/28
var_rtr_b:
subnet: 10.10.2.0/28
I tried it with this code我用这段代码试过了
key = ['subnet']
values = list(map(mydictionray.get, keys)
# Output: [none]
I understand why the output is None
, because the key is not correct.我理解为什么 output 是None
,因为密钥不正确。 But how can I define the correct key?但是我怎样才能定义正确的键呢?
That's a dict of dicts.那是字典的字典。
Go for a recursive solution: Go 用于递归解决方案:
def recursive_key_search(key, lookup):
if isinstance(lookup, dict):
for _key in lookup.keys():
if _key == key:
output.append(lookup[key])
recursive_key_search(key, lookup[_key])
Sample use:样品用途:
test_dict = {
'a': 'b',
'c': {'d': 'e'}
}
output = []
recursive_key_search('d', test_dict)
print(output)
# >>> ['e']
i have edit my code into a function.我已将我的代码编辑为 function。 Data is the dictionary数据就是字典
def search_dict(data):
keys=['var_rtr_a','subnet','var_rtr_b','subnet']
output=list(map(data.get,keys))
print(output)
return output
Output: [{'subnet': '10.10.1.0/28'}, None, {'subnet': '10.10.2.0/28'}, None]
But this is not what i need, i need only the values from the keys..但这不是我需要的,我只需要键中的值..
The way your data is formatted has it with a dictionary inside of a dictionary.格式化数据的方式具有字典内的字典。 When you look for subnet
, you're only looking at the first layer of dictionaries, and not the second where subnet belongs.当您查找subnet
时,您只查看第一层字典,而不是子网所属的第二层。
One way of amending this that I can think of would be to iterate through the exterior values of the dictionary, and then search for subnet inside of those:我能想到的一种修改方法是遍历字典的外部值,然后在其中搜索子网:
def search_dict(data):
output = []
for k in data:
try:
output.append(data[k]['subnet'])
return output
This will correctly get every subnet from the dictionary and output it to a list.这将正确地从字典中获取每个子网,并将 output 到列表中。
Output:
['10.10.1.0/28', '10.10.1.0/28']
i changed my code to your example, but is does not work.我将代码更改为您的示例,但不起作用。
def search_dict(data):
output = []
for k in data:
#try:
output.append(data[k]['subnet'])
return output
if __name__ == '__main__':
data = read_file("data_input.yaml")
search_dict(data)
subnet = search_dict(data)
print(subnet)
Output:
29 for k in data:
30 #try:
---> 31 output.append(data[k]['subnet'])
32 #print(output)
33 return output
KeyError: 'subnet'
Can we check the code again我们可以再次检查代码吗
ok, i try it with filtering with an example from this post:好的,我尝试使用这篇文章中的示例进行过滤:
How to filter a nested dictionary (pythonic way) for a specific value using map or filter instead of list comprehensions? 如何使用 map 或过滤器而不是列表推导过滤特定值的嵌套字典(pythonic 方式)?
But it doesnt work with my dict.但它不适用于我的听写。
Here my tests: Checks:这是我的测试: 检查:
In [6]: data.values()
Out[6]: dict_values([{'rt_id': 12345}, {'subnet': '10.10.1.0/28'}, {'subnet': '10.10.2.0/28'}])
In [7]: data.items()
Out[7]: dict_items([('global_var', {'rt_id': 12345}), ('var_rtr_a', {'subnet': '10.10.1.0/28'}), ('var_rtr_b', {'subnet': '10.10.2.0/28'})])
In [8]: data.keys()
Out[8]: dict_keys(['global_var', 'var_rtr_a', 'var_rtr_b'])
In [11]: type(data)
Out[11]: dict
Here my filter with error:
In [12]: list(filter(lambda x: x['subnet'] , data.values()))
KeyError: 'subnet'
In [3]: list(filter(lambda x: x['var_rtr_a']['subnet'], data.values()))
KeyError: 'var_rtr_a'
Question: what is the right key for the filter?问题:过滤器的正确键是什么? and wy is subnet not a right key?为什么子网不是正确的键?
So when i have an eays dict.所以当我有一个 eays dict 时。 the filters works fine过滤器工作正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.