问题
I am new to Python and I am struggling with printing multiple nested dictionaries in one table separated by tab.
I wrote a script to read data from an input file and store the data in 3 different dictionaries:
d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'}, 'Tom': {'Skill': 'true', 'Magic': 'true'}}
d2 = {'Ben': {'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'}, 'Tom': {'Int': 'wi_mana', 'Agility': 'wo_mana'}}
d3 = {'Ben': {'Strength': '1.10', 'Int': '1.20', 'Speed': '1.50'}, 'Tom': {'Int': '1.40', 'Agility': '1.60'}}
I want to represent the data in a table format and when opened in Excel, it looks something like this:
Name Skill Magic wo_mana wi_mana
Ben true false Strength = 1.10 Int = 1.20
Speed = 1.50
Tom true true Agility = 1.60 Int = 1.40
So my desired output in the output file should be like this:
Name\tSkill\tMagic\two_mana\twi_mana
Ben\ttrue\tfalse\tStrength = 1.10\tInt = 1.20
\t\t\tSpeed = 1.50\t
Tom\ttrue\ttrue\tAgility = 1.60\tInt = 1.40
I am aware that I could do this using the csv
module but it looks like it wouldn't make sense for multiple rows for a record in csv
so I have decided to try string formatting
.
I tried my best and this is what I have written so far:
print('Name\tSkill\tMagic\two_mana\twi_mana\n')
for key in d1:
print('%s\t%s\t%s' %(key, d1[key]['Skill'], d1[key]['Magic']))
and it works well for the first 3 columns, Name, Skill and Magic
.
My question is how am I supposed to print the wo_mana
and wi_mana
data into the same table? Should I change my dictionaries to:
d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'}, 'Tom': {'Skill': 'true', 'Magic': 'true'}}
d23 = {'Ben': {'wo_mana': 'Strength = 1.10', 'wi_mana': 'Int = 1.20', 'wo_mana': 'Speed = 1.50'}, 'Tom': {'wi_mana': 'Int = 1.40', 'wo_mana': 'Agility = 1.60'}}
so that they are easier to print with string formatting
?
EDIT:
If my dictionaries is in this form:
d123 = {'Ben': {'wo_mana': ['Strength = 1.10', 'Speed = 1.50'], 'wi_mana': ['Int = 1.20'], 'Skill': 'true', 'Magic': 'false'},
'Tom': {'wi_mana': ['Int = 1.40'], 'wo_mana': ['Agility = 1.60'], 'Skill': 'true', 'Magic': 'true'}}
would it be easier?
I tried to write my code for d123
but it is still not working for me:
for key in d123_new:
print('%s\t%s\t%s\t%s' %(d123_new[key]['Skill'], d123_new[key]['Magic'], x for x in d123_new[key]['wo_mana'], y for y in d123_new[key]['wi_mana']))
Please show me how to print the data in the table format that I mentioned above, I have tried everything that I could think of, any help would be greatly appreciated!
来源:https://stackoverflow.com/questions/38080975/python-writing-multiple-nested-dictionaries-in-one-table-in-a-text-file-separat