简体   繁体   中英

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.

#!/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() :

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.

You should read the documentation for how to open and write to file. It is very straight forward in python. Assuming you are using python 2.7, here is the link: 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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