2015-11-07 175 views
0

我想弄清楚如何從API調用中獲取所有字典鍵,並將它們插入到平面文件中。python:將字典鍵打印到文件

#!/usr/bin/env python 

import requests 
import json 
import time 
import urllib3 
from base64 import b64encode 

requests.packages.urllib3.disable_warnings() 


# 
# GET /dashboards/{dashboardId}/widgets/{widgetId}/value 
test_dashboard = "557750bee4b0033aa111a762" 
test_widget = "8bad2fc0-5c9b-44f2-a54b-05c8c6f9552b" 
apiserver = "http://serveraddress" 
userpass = b64encode(b"myuser:mypass").decode("ascii") 
headers = { 'Authorization' : 'Basic %s' % userpass } 

def get_apicall(dashboardId, widgetId): 
    response = requests.get(
          apiserver + "/dashboards/" + 
          dashboardId + "/widgets/" + 
          widgetId + "/value", 
          headers=headers, 
          verify=False) 
    json_data = json.loads(response.text) 
    print(json.dumps(json_data["result"]["terms"], indent=2)) 

get_apicall(test_dashboard, test_widget) 

,其輸出是這樣的:

[[email protected] ]$ ./shunhosts.py 
{ 
    "71.6.216.39": 2, 
    "71.6.158.166": 2, 
    "71.6.216.55": 2, 
    "71.6.216.56": 2 
} 

我想代碼寫/追加每個字典鍵,新的生產線的純文本文件:即

71.6.216.39 
71.6.158.166 
71.6.216.55 
71.6.216.56 
+0

有一個'keys()'方法 – tuxtimo

回答

3

如果你有一本字典作爲

d = { 
    "71.6.216.39": 2, 
    "71.6.158.166": 2, 
    "71.6.216.55": 2, 
    "71.6.216.56": 2 
} 

你可以讓你的鑰匙keys()

d.keys() 
dict_keys(['71.6.216.56', '71.6.216.39', '71.6.158.166', '71.6.216.55']) 

使它成爲一個新行sep arated:

s = '\n'.join(d.keys()) 
print(s) 
71.6.216.39 
71.6.158.166 
71.6.216.55 
71.6.216.56 

然後寫入文件:

with open('some_file.txt', 'w') as fw: 
    fw.write(s) 

您現在可以進一步簡化這:

with open('some_file.txt', 'w') as fw: 
    fw.write('\n'.join(d.keys())) 
0

字典是,根據定義,鍵任意數量的。沒有「關鍵」。你,讓你的所有鍵的Python列表鍵()方法,你必須theiteritems()方法,它返回鍵 - 值對,所以

for key, value in mydic.iteritems() : 
    thefile.write("%s\n" % key) 

或者乾脆你可以做到這一點

for key in mydic.keys(): 
    thefile.write("%s\n" % key)