简体   繁体   English

python:将字典键打印到文件

[英]python: print dictionary keys to a file

I'd like to figure out how to take all dictionary keys from an API call, and insert them into a flat 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)

which outputs something like: 输出类似:

[user@host ]$ ./shunhosts.py 
{
  "71.6.216.39": 2, 
  "71.6.158.166": 2, 
  "71.6.216.55": 2, 
  "71.6.216.56": 2
}

I would like the code to write/append each dictionary key to new line in a flat text file: ie 我希望代码将每个字典键写入/附加到纯文本文件中的新行:即

71.6.216.39
71.6.158.166
71.6.216.55
71.6.216.56

If you have a dictionary as 如果您有字典

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

You can get your keys with keys() : 您可以使用keys()获取密钥:

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

Make it to a string that is new-line separated: 将其设置为以换行符分隔的字符串:

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

Then write it to a file: 然后将其写入文件:

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

You can now further simplify this to: 现在,您可以进一步简化为:

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

json_data["result"]["terms"].keys() should give you all the keys. json_data["result"]["terms"].keys()应该为您提供所有密钥。

You should read the documentation for how to open and write to file. 您应该阅读有关如何打开和写入文件的文档。 It is very straight forward in python. 在python中非常简单。 Assuming you are using python 2.7, here is the link: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files 假设您使用的是python 2.7,则这里是链接: https : //docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

It would be something like this: 就像这样:

f = open(filename, 'w')
f.write(json_data["result"]["terms"].keys())
f.close()

A dictionary has, by definition, an arbitrary number of keys. 根据定义,字典具有任意数量的键。 There is no "the key". 没有“钥匙”。 You have the keys() method, which gives you a python list of all the keys, and you have theiteritems() method, which returns key-value pairs, so 您具有keys()方法,该方法为您提供所有键的python列表,并且您具有theiteritems()方法,该方法返回键-值对,因此

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

Or simply you can do this 或者干脆你可以做到这一点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM