格式化字典python2

时间:2018-04-21 09:17:46

标签: python python-2.7 formatting string-formatting file-writing

我有一个网络服务器,当您卷曲日志时,会提供以下示例数据。

curl http://10.10.10.10.server1.com/logs

结果

[{"Database":"Database2","Version":"0.1.2","Day_time":329477060,"My_count":102075020,"ProjectID":55358627,"Final_time":46716393},
{"Database":"Database200","Version":"0.1.0","Day_time":5167727780,"My_count":4724597678,"ProjectID":1708358878,"Final_time":3016238800},
{"Database":"Database1","Version":"1.1.1","Day_time":1647140700,"My_count":7833711472,"ProjectID":5241471510,"Final_time":2592239962},
{"Database":"Database201","Version":"0.2.2","Day_time":2490677104,"My_count":7525799955,"ProjectID":1849565089,"Final_time":5676234866},
{"Database":"Cache1","Version":"1.2.2","Day_time":6877694221,"My_count":7403116508,"ProjectID":3260475032,"Final_time":4142641476},
{"Database":"Database201","Version":"1.2.1","Day_time":8285487311,"My_count":2970023201,"ProjectID":2956709247,"Final_time":13313954},
{"Database":"Database202","Version":"0.0.1","Day_time":5032945971,"My_count":2453463265,"ProjectID":932154161,"Final_time":1521309104},
{"Database":"Database202","Version":"1.2.1","Day_time":6440876717,"My_count":609847918,"ProjectID":364440252,"Final_time":245407666},
{"Database":"Cache1","Version":"0.0.3","Day_time":2265003223,"My_count":7311023147,"ProjectID":4612143282,"Final_time":2698879865},
{"Database":"Database202","Version":"0.0.1","Day_time":8743007122,"My_count":7687687281,"ProjectID":4160318641,"Final_time":3527368640},
{"Database":"Cache1","Version":"1.1.2","Day_time":9281660375,"My_count":4028121672,"ProjectID":3240617982,"Final_time":787503690}]

我想从此日志中获取数据库,版本和Final_time。

以下是我的代码。

from urllib2 import Request, urlopen, URLError
import json

# Read file, Execute REST api request then parse output

file = open("list_0f_servers.txt")
for host in hosts:
    link = 'http://%s.server1.com/logs' % (server)
    requestLink = Request(link)
    try:
        requestResponse = urlopen(requestLnk)
        resultJson = responseResponse.read()
        resultArray = []
        jsonData = json.loads(resultJson)
        for dict in jsonData:
            tempDict = {}
            for key, val in dict.iteritems():
                if key.find('Database') != -1 or key.find('Version') != -1 or key.find('Final_time') != -1:
                    tempDict[key] = val
            resultArray.append(tempDict)
            print tempDict
    except URLError, e:
        print 'Got an error code:', e
file.close()

我能够达到低于结果的水平。

{u'Database': u'Webapp1', u'Version': u'1.1.0', u'Final_time': 5729616276}
{u'Database': u'Cache0', u'Version': u'0.0.1', u'Final_time': 412280130}
{u'Database': u'Cache2', u'Version': u'0.1.1', u'Final_time': 967336228}
{u'Database': u'Cache0', u'Version': u'1.1.2', u'Final_time': 4443384438}
{u'Database': u'Database1', u'Version': u'0.2.2', u'Final_time': 782303822}
{u'Database': u'Cache0', u'Version': u'0.2.1', u'Final_time': 1490849761}
{u'Database': u'Webapp2', u'Version': u'1.1.2', u'Final_time': 4874374574}

但我希望将其格式化为更易读的格式,如下所示,并将其写入文件。所以它应该显示并写入输出到文件。

Database Webapp1 Version 1.1.0 Final_time 5729616276
Database Cache0 Version 0.0.1 Final_time 412280130
Database Cache2 Version 0.1.1 Final_time 967336228
Database Cache0 Version 1.1.2 Final_time 4443384438
Database Database1 Version 0.2.2 Final_time 782303822
Database Cache0 Version 0.2.1 Final_time 1490849761
Database Webapp2 Version 1.1.2 Final_time 4874374574 

非常感谢任何帮助。谢谢。

3 个答案:

答案 0 :(得分:1)

这样的事情会起作用吗?

def prettify(d, exclude=['ProjectID', 'My_count', 'Date_time']):
    res = ''

    for k, v in d.items():
        if k in exclude:
            continue
        res += ' {} {}'.format(k, v)
    return res

答案 1 :(得分:1)

您可以执行以下操作:

out = ['ProjectID', 'My_count', 'Date_time']
print(" ".join(["{} {}".format(k, v) for k, v in x.items() if k not in out]))

对于Python 2:

print " ".join(["{} {}".format(k, v) for k, v in x.iteritems() if k not in out])

答案 2 :(得分:1)

如果您想按特定顺序从字典中提取字段,最好列出您想要的密钥而不是您不想要的密钥(与前两个答案提出的方法相反)。所以我建议:

dicts = [{"Database":"Database2","Version":"0.1.2","Day_time":329477060,"My_count":102075020,"ProjectID":55358627,"Final_time":46716393}, "Database":"Database200","Version":"0.1.0","Day_time":5167727780,"My_count":4724597678,"ProjectID":1708358878,"Final_time":3016238800}, "Database":"Database1","Version":"1.1.1","Day_time":1647140700,"My_count":7833711472,"ProjectID":5241471510,"Final_time":2592239962},{"Database":"Database201","Version":"0.2.2","Day_time":2490677104,"My_count":7525799955,"ProjectID":1849565089,"Final_time":5676234866},{"Database":"Cache1","Version":"1.2.2","Day_time":6877694221,"My_count":7403116508,"ProjectID":3260475032,"Final_time":4142641476},{"Database":"Database201","Version":"1.2.1","Day_time":8285487311,"My_count":2970023201,"ProjectID":2956709247,"Final_time":13313954},{"Database":"Database202","Version":"0.0.1","Day_time":5032945971,"My_count":2453463265,"ProjectID":932154161,"Final_time":1521309104},{"Database":"Database202","Version":"1.2.1","Day_time":6440876717,"My_count":609847918,"ProjectID":364440252,"Final_time":245407666},{"Database":"Cache1","Version":"0.0.3","Day_time":2265003223,"My_count":7311023147,"ProjectID":4612143282,"Final_time":2698879865}, "Database":"Database202","Version":"0.0.1","Day_time":8743007122,"My_count":7687687281,"ProjectID":4160318641,"Final_time":3527368640}, "Database":"Cache1","Version":"1.1.2","Day_time":9281660375,"My_count":4028121672,"ProjectID":3240617982,"Final_time":787503690}]

keys = "Database Version Final_time".split()
result = '\n'.join(' / '.join(("%s %s" % (k,d[k]) for k in keys)) for d in dicts)
print(result)

结果:

Database Database2 / Version 0.1.2 / Final_time 46716393
Database Database200 / Version 0.1.0 / Final_time 3016238800
Database Database1 / Version 1.1.1 / Final_time 2592239962
Database Database201 / Version 0.2.2 / Final_time 5676234866
Database Cache1 / Version 1.2.2 / Final_time 4142641476
Database Database201 / Version 1.2.1 / Final_time 13313954
Database Database202 / Version 0.0.1 / Final_time 1521309104
Database Database202 / Version 1.2.1 / Final_time 245407666
Database Cache1 / Version 0.0.3 / Final_time 2698879865
Database Database202 / Version 0.0.1 / Final_time 3527368640
Database Cache1 / Version 1.1.2 / Final_time 787503690

注意:我添加了斜杠/以提高可读性,但如果您不想要/不需要,可以在join声明中将其删除