2017-08-10 72 views
0

我有這樣的JSON,我想只提取把所有的ID在字典生成列表follower_ids WRT PROJECT_ID到一個列表如下:通過使用python

followers_ids_for_01 = [123,124,...] 
followers_ids_for_02 = [125,126,...] 

的Json列表:

{ 
    "data": [{ 
     "id": 01, 
     "followers": [{ 
      "id": 123, 
      "name": "Shivkumar" 
     }, { 
      "id": 124, 
      "name": "Sneha" 
     }, 
     { 
      ..... 
     }], 
    }, { 
     "id": 02, 
     "followers": [{ 
      "id": 125, 
      "name": "Teja" 
     }, { 
      "id": 126, 
      "name": "Harsha" 
     }, 
     { 
      ...... 
     }], 
    }] 
} 

我試過的:

data =json_list 
projects = data['data'] 

followers_ids =[] 
for project in projects: 
    for i in project['followers']: 
     followers_ids.append(i['id']) 

print followers_ids 

輸出:

[123, 124, 125, 126] 

有人建議如何產生「followers_ids_for_{project_id}」列表,並添加其各自的追隨者IDS的呢?

編輯/更新:

我需要生成命名變量空白列表

datalists = dict() 
for project in projects: 
    datalists["followers_ids_for_{}".format(project['id'])] = [] 

print datalists 
#{'followers_ids_for_1': [], 'followers_ids_for_2': []} 
+1

您將需要一本字典,否則不能「生成列表」。 –

+0

是的..我已經通過一些其他答案,如https:// stackoverflow。com/a/42768290/6107715我還在尋找一種解決方案,我可以獲得命名空白列表 –

+1

您的意思是,您想要有許多單獨的變量名稱「followers_ids_for_01」,「followers_ids_for_02」等等? –

回答

1

你要做的第一件事是建立在格式你想要一本字典:

In [514]: f = {'followers_ids_for_%s' %d['id'] : [x['id'] for x in d['followers']] for d in data['data'] }; f 
Out[514]: {'followers_ids_for_01': [123, 124], 'followers_ids_for_02': [125, 126]} 

我建議你在此停止。但是,這裏是第二個,並且高度不推薦步驟(來自您的hard requirement):更新globals()

In [516]: globals().update(f) 

In [517]: followers_ids_for_01 
Out[517]: [123, 124] 

現在您可以以列表的形式訪問這些變量。再次,這是不好的,因爲它會污染你的全局變量。

+0

其實我試圖瞭解這個場景的列表的用法和限制。你已經給出了這樣一個更好的解釋。非常感謝 –

+0

@BHappyBHarsham我很高興你接受了其他答案,但我認爲這是你想要的。 –

1

你可以使用一個列表理解,而不是

[follower['id'] for project in projects for follower in project['followers']] 

如果你只關心一個特定的項目ID

[follower['id'] for project in projects for follower in project['followers'] if project['id] == 'some id'] 
1

您可以使用嵌套字典理解表達式創建dict object`:

>>> {val['id']: [item['id'] for item in val['followers']] for val in data['data']} 
{1: [123, 124], 2: [125, 126]} 

假設上述字典存儲在變量result。然後,你可以訪問該元素在字典對應於每個所謂的項目編號爲:

>>> result[1] # For id '1' 
[123, 124] 

>>> result[2] # For id '2' 
[125, 126] 

PS:在上面的字典理解data變量保存您的JSON對象的值,即:

{ 
    "data": [{ 
     "id": 1, 
     "followers": [{ 
      "id": 123, 
      "name": "Shivkumar" 
     }, { 
      "id": 124, 
      "name": "Sneha" 
     }], 
    }, { 
     "id": 2, 
     "followers": [{ 
      "id": 125, 
      "name": "Teja" 
     }, { 
      "id": 126, 
      "name": "Harsha" 
     }] 
    }] 
} 
+1

感謝這樣更好的解釋 –