【发布时间】:2014-07-19 14:55:15
【问题描述】:
我有一个复杂的多维字典,我想将一些键值对导出到 csv 文件作为运行日志文件。我已经尝试了有关导出到 cvs 函数的各种帮助,并破解了 stackoverflow 中关于遍历多维字典的大部分代码示例,但未能找到解决方案。这个问题也很独特,因为它只有一些我想导出的键值。
这是字典:
cpu_stats = {'time_stamp': {'hour': 22, 'month': 5, 'second': 43, 'year': 2014, 'day': 29, 'minute': 31}, 'cpus': [[{'metric_type': 'CPU_INDEX', 'value': 1}, {'metric_type': 'CPU_TEMPERATURE', 'value': 39}, {'metric_type': 'CPU_FAN_SPEED', 'value': 12000}]]}
我需要将 time_stamp 中的值格式化为 yyyy-mm-dd hh:mm:ss 并将其存储为行的第一个单元格。然后,我需要 CPU_INDEX、CPU_TEMPERATURE 和 CPU_FAN_SPEED 在“cpus”中的值与时间戳在同一行中。
csv 文件应如下所示:
time_stamp, cpu_index, cpu_temperature, cpu_fan_speed
2014-05-29, 1, 38, 12000
我一直在破解的一个例子是:
def walk_dict(seq, level=0):
"""Recursively traverse a multidimensional dictionary and print all
keys and values.
"""
items = seq.items()
items.sort()
for v in items:
if isinstance(v[1], dict):
# Print the key before make a recursive call
print "%s%s" % (" " * level, v[0])
nextlevel = level + 1
walk_dict(v[1], nextlevel)
else:
print "%s%s %s" % (" " * level, v[0], v[1])
我得到以下输出
walk_dict(cpu_stats)
cpus [[{'metric_type': 'CPU_INDEX', 'value': 1}, {'metric_type': 'CPU_TEMPERATURE', 'value': 38}, {'metric_type': 'CPU_FAN_SPEED', 'value': 12000}]]
time_stamp
day 29
hour 22
minute 17
month 5
second 19
year 2014
我也一直在破解这个函数,希望我可以将日期信息存储到变量中,然后可以将其格式化为单个字符串。不幸的是,它具有递归调用,这会在后续调用中丢失局部变量。使用全局是徒劳的。
def parseDictionary(obj, nested_level=0, output=sys.stdout):
spacing = ' '
if type(obj) == dict:
print >> output, '%s{' % ((nested_level) * spacing)
for k, v in obj.items():
if hasattr(v, '__iter__'):
# 1st level, prints time and cpus
print >> output, '%s:' % (k)
parseDictionary(v, nested_level + 1, output)
else:
# here is the work
if k == "hour":
hour = v
elif k == "month":
month = v
elif k == "second":
second = v
elif k == "year":
year = v
elif k == "day":
day = v
elif k == "minute":
minute = v
print >> output, '%s %s' % (k, v)
print >> output, '%s}' % (nested_level * spacing)
elif type(obj) == list:
print >> output, '%s[' % ((nested_level) * spacing)
for v in obj:
if hasattr(v, '__iter__'):
parseDictionary(v, nested_level + 1, output)
else:
print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
print >> output, '%s]' % ((nested_level) * spacing)
else:
print >> output, '%s%s' % (nested_level * spacing, obj)
if __name__ == "__main__":
global year
global month
global day
global hour
global minute
global second
cpu_stats = {'time_stamp': {'hour': 22, 'month': 5, 'second': 43, 'year': 2014, 'day': 29, 'minute': 31}, 'cpus': [[{'metric_type': 'CPU_INDEX', 'value': 1}, {'metric_type': 'CPU_TEMPERATURE', 'value': 39}, {'metric_type': 'CPU_FAN_SPEED', 'value': 12000}]]}
parseDictionary(cpu_stats)
print '%s-%s-%s %s:%s:%s' % (year, month, day, hour, minute, second)
输出:
{
time_stamp:
{
hour 22
month 5
second 27
year 2014
day 29
minute 57
cpus:
[
[
{
metric_type CPU_INDEX
value 1
{
metric_type CPU_TEMPERATURE
value 39
{
metric_type CPU_FAN_SPEED
value 12000
]
]
Traceback (most recent call last):
File "./cpu.py", line 135, in <module>
print '%s-%s-%s %s:%s:%s' % (year, month, day, hour, minute, second)
NameError: global name 'year' is not defined
谢谢,感谢您为我指明正确方向的任何帮助,因为我目前不知所措。
【问题讨论】:
标签: python dictionary multidimensional-array export-to-csv