[英]python: print dictionary keys to a file
我想弄清楚如何從API調用中獲取所有字典鍵,並將其插入到平面文件中。
#!/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)
輸出類似:
[user@host ]$ ./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
如果您有字典
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'])
將其設置為以換行符分隔的字符串:
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()))
json_data["result"]["terms"].keys()
應該為您提供所有密鑰。
您應該閱讀有關如何打開和寫入文件的文檔。 在python中非常簡單。 假設您使用的是python 2.7,則這里是鏈接: https : //docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
就像這樣:
f = open(filename, 'w')
f.write(json_data["result"]["terms"].keys())
f.close()
根據定義,字典具有任意數量的鍵。 沒有“鑰匙”。 您具有keys()方法,該方法為您提供所有鍵的python列表,並且您具有theiteritems()方法,該方法返回鍵-值對,因此
for key, value in mydic.iteritems() :
thefile.write("%s\n" % key)
或者干脆你可以做到這一點
for key in mydic.keys():
thefile.write("%s\n" % key)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.