如何从多个字典的列表中获取特定值

时间:2021-02-19 10:02:18

标签: python python-3.x dictionary

I have a list of dictionaries as 

    check_list = [{'datasource_path': 'Checks/',
      'Result': True,
      'kwargs': {'column_name': 'car_id', 'd_type': 'int', 'table': 'cars/'},
      'type': 'check_datatype'},
     {'datasource_path': 'Checks1/',
       'Result': False,
      'kwargs': {'column_name': 'customer_id', 'd_type': 'str', 'table': 'cars1/'},
      'type': 'check_datatype1'}]
    
I was trying this:  

     res = [[i for i in check_dict[x]] for x in check_dict.keys()] 
     print("The list values of keys are : " + str(res)) 
    
what I want to get as output is list of lists as below:
    
    [[ Checks/,True,'cars/',check_datatype],[ 

Checks1/,False,'cars1/',check_datatype1]]

I have one more use case where the below function takes 'type' as argument 
and returns the corresponding value as per dictionary 

def getType(self,type):
        check_dict={'check_datatype':'M1','check_datatype1':'C1'
                    }
        return check_dict[test_case_name] 
  

我想根据类型附加此字典值 M1 和 C1 所有列表输出。最终输出应如下所示 -

[['Checks/', True, 'cars/', 'check_datatype','M1'], ['Checks1/', False, 
'cars1/', 'check_datatype1','C1']]

4 个答案:

答案 0 :(得分:0)

简单地使用列表理解为:

lst = [{'datasource_path': 'Checks/',
  'Result': True,
  'kwargs': {'column_name': 'car_id', 'd_type': 'int', 'table': 'cars/'},
  'type': 'check_datatype'},
 {'datasource_path': 'Checks1/',
   'Result': False,
  'kwargs': {'column_name': 'customer_id', 'd_type': 'str', 'table': 'cars1/'},
  'type': 'check_datatype1'}]

res = [[elt['datasource_path'], elt['Result'], elt['kwargs']['table'], 
       elt['type']] for elt in lst]

print(res)

输出:

[['Checks/', True, 'cars/', 'check_datatype'], ['Checks1/', False, 'cars1/', 'check_datatype1']]

仅使用 keys() 将不起作用,因为它是一个嵌套字典,因此 keys() 将仅提供键级别。


更新:根据数据类型添加另一个元素。

def getType(check_type): 
    check_dict={'check_datatype':'M1','check_datatype1':'C1' } 
    return check_dict[check_type] 

res = [[elt['datasource_path'], elt['Result'], elt['kwargs']['table'], elt['type'], getType(elt['type'])] for elt in lst]

print(res)

输出:

[['Checks/', True, 'cars/', 'check_datatype', 'M1'], ['Checks1/', False, 'cars1/', 'check_datatype1', 'C1']]

答案 1 :(得分:0)

如果你有嵌套字典,你可以检查键的值是否是字典,然后你可以遍历它。

check_list = [{'datasource_path': 'Checks/', 'Result': True, 'kwargs': {'column_name': 'car_id', 'd_type': 'int', 'table': 'cars/'}, 'type': 'check_datatype'}, {'datasource_path': 'Checks1/', 'Result': False, 'kwargs': {'column_name': 'customer_id', 'd_type': 'str', 'table': 'cars1/'}, 'type': 'check_datatype1'}]
check_list

outer_answer = []

for check_dict in check_list:
    inner_answer = []
    for k,v in check_dict.items():
        if isinstance(v, dict):
            inner_answer.append(v["table"])
        else:
            inner_answer.append(v)
    outer_answer.append(inner_answer)
            
print(outer_answer)

输出:

[['Checks/', True, 'cars/', 'check_datatype'], ['Checks1/', False, 'cars1/', 'check_datatype1']]

答案 2 :(得分:0)

这是一个使用循环、isinstance()、字典键和 enumerate() 的有效解决方案。


check_list = [{'datasource_path': 'Checks/', 'Result': True, 'kwargs': {'column_name': 'car_id', 'd_type': 'int', 'table': 'cars/'}, 'type': 'check_datatype'},
              {'datasource_path': 'Checks1/', 'Result': False, 'kwargs': {'column_name': 'customer_id', 'd_type': 'str', 'table': 'cars1/'}, 'type': 'check_datatype1'}]
solution, values = [], []

for i, item in enumerate(check_list):
    for key in item.keys():
        if not isinstance(check_list[i][key], dict):
            values.append(check_list[i][key])
    solution.append(values)
    values = []
print(solution)

输出等于:

[['Checks/', True, 'check_datatype'], ['Checks1/', False, 'check_datatype1']]

谢谢

答案 3 :(得分:0)

如果你想使用嵌套的 for 循环,你必须检查你的值是否是一个 dict,然后选择哪个键。这可以通过以下代码完成:

res = [[(value["table"] if isinstance(value, dict) else value) for value in d.values()] for d in check_list]
print(res)

输出:

[['Checks/', True, 'cars/', 'check_datatype'], ['Checks1/', False, 'cars1/', 'check_datatype1']]