[英]Writing a Python Dictionary to CSV
hope you can help me with this.希望你能帮助我。
I have a nested dictionary like this:我有一个这样的嵌套字典:
Inventory = {'devicename': {'Interface1': {'port_setting1': 'value', 'port_setting2': 'value'}, 'Interface2': {'port_setting1': 'value', 'port_setting2': 'value'}}}
I want to create a csv out of that with the following format:我想用以下格式创建一个 csv :
devicename, interface1, value of port_setting1, value of portsetting2
devicename, interface2, value of port_setting1, value of portsetting2
Can you help me how to handle this?你能帮我解决这个问题吗?
Thanks!谢谢!
You can import the dictionary to a pandas dataframe.您可以将字典导入 pandas dataframe。 This can then be exported as a csv without the column names to achieve what you require.然后可以将其导出为 csv 没有列名来实现您的要求。
The following code snippet would do the trick:以下代码片段可以解决问题:
import pandas as pd
df = pd.DataFrame.from_dict({(i,j): Inventory[i][j]
for i in Inventory.keys()
for j in Inventory[i].keys()},
orient='index')
df.to_csv('test.csv', header = False)
This is how your test.csv
looks like for the dictionary called Inventory
you have shown in the question:这就是您在问题中显示的名为Inventory
的字典的test.csv
的样子:
devicename,Interface1,value,value
devicename,Interface2,value,value
You can loop through the dict
and print
in a file:您可以遍历dict
并在文件中print
:
with open(filename.csv, 'w') as fh:
for k, v in Inventory.items():
for k1, v1 in v.items():
print(k, k1, *v1.values(), file=fh, sep=', ')
Or in a comprehension:或者理解为:
with open(filename.csv, 'w') as fh:
print(*(', '.join((k, k1, *v1.values()))
for k, v in Inventory.items()
for k1, v1 in v.items()),
file=fh, sep='\n'
)
Output: Output:
devicename, Interface1, value, value
devicename, Interface2, value, value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.