Python:遍历字典列表并输出到列表

时间:2019-09-05 22:12:42

标签: python

我正在遍历json对象,并且该对象的输出采用字典列表的形式。

[{'Status': 'active', 'id': '0f1fb86da9c7ee380'}]
[{'Status': 'active', 'id': '0d6b330e4960c3382'}, {'Status': 'active', 'id': '033cfb634e595ccfa'}]
[{'Status': 'active', 'id': '0457f623cbb9f7c95'}]
[{'Status': 'active', 'id': '01b69eb6a3048f749'}, {'Status': 'active', 'id': '0f7ce44a9a5fc82f5'}, {'Status': 'active', 'id': '05417e161acf3ec5d'}]
[{'Status': 'active', 'id': '033cfb634e595ccfa'}, {'Status': 'active', 'id': '01eab32f9808acf19'}]

到目前为止,我已经尝试过类似的方法,但是它以字符串形式打印。我尝试使用列表并附加它,但是它给了我一个奇怪的输出。如果我不使用列表,那么它将以字符串的形式提供所有列表。

当前输出:

0f1fb86da9c7ee380
0d6b330e4960c3382
033cfb634e595ccfa
0457f623cbb9f7c95
01b69eb6a3048f749
0f7ce44a9a5fc82f5
05417e161acf3ec5d
0f373f123dc8221de
05417e161acf3ec5d

我的代码:

    for i in data['DBI']:
        t = 0
         while t < len(i['Groups']):
             print i['Groups'][t]['id']
             t += 1` 

预期的输出:我正在寻找像这样的列表['0f1fb86da9c7ee380'] ['0d6b330e4960c3382','033cfb634e595ccfa'] ['0457f623cbb9f7c95'] ['01b69eb6a3048f749','0f7ce44a9a5fc82f5',''05417e161acf3ec5d'] ['033cfb634e595ccfa','01eab32f9808acf19']

3 个答案:

答案 0 :(得分:1)

您想要的是这样的

data = [ 
    [{'Status': 'active', 'id': '0f1fb86da9c7ee380'}], 
    [{'Status': 'active', 'id': '0d6b330e4960c3382'}, {'Status': 'active', 'id': '033cfb634e595ccfa'}], 
    [{'Status': 'active', 'id': '0457f623cbb9f7c95'}], 
    [{'Status': 'active', 'id': '01b69eb6a3048f749'}, {'Status': 'active', 'id': '0f7ce44a9a5fc82f5'}, {'Status': 'active', 'id': '05417e161acf3ec5d'}], 
    [{'Status': 'active', 'id': '033cfb634e595ccfa'}, {'Status': 'active', 'id': '01eab32f9808acf19'}], 
]   

new_data = [] 
   for l in data: 
       current_ids = [] 
       for d in l: 
           current_ids.append(d["id"]) 
       new_data.append(current_ids) 
new_data

输出:

[['0f1fb86da9c7ee380'],
 ['0d6b330e4960c3382', '033cfb634e595ccfa'],
 ['0457f623cbb9f7c95'],
 ['01b69eb6a3048f749', '0f7ce44a9a5fc82f5', '05417e161acf3ec5d'],
 ['033cfb634e595ccfa', '01eab32f9808acf19']]

答案 1 :(得分:1)

您还可以使用列表理解来实现这一目标。

output = [[item["id"] for item in items] for items in data]

答案 2 :(得分:0)

data =json.loads(v_string)
for id in data['DBI']:
  datalist = id['Groups']
  i=0
  data_list=[]   #<-- This was outside above mann for loop.
  while i < len(datalist):
    for dic in datalist[i]:
          if 'active' not in datalist[i][dic]:
          data_list.append(datalist[i][dic])
          print(data_list)
    i+=1