python:将字典键打印到文件中

时间:2015-11-07 00:01:50

标签: python dictionary

我想弄清楚如何从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

3 个答案:

答案 0 :(得分: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'])

将其设为新行分隔的字符串:

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()))

答案 1 :(得分:0)

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()

答案 2 :(得分:0)

根据定义,字典具有任意数量的键。没有“钥匙”。你有keys()方法,它给你一个所有键的python列表,你有theiteitems()方法,它返回键值对,所以

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

或者只是你可以这样做

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