Reputation: 2619
I have these single-line dictionaries which is read from standard input.
def gen_with appropriate_name():
for n, line in enumerate(sys.stdin):
d = ast.literal_eval(line)
items = d.values()[0].items()
items.sort(key = lambda itm: itm[0])
yield {n+1: {i+1:item[1] for i, item in enumerate(items)}}
d = gen_with appropriate_name() # prime the generator
d.next()
for thing in d:
print thing
If you print 'd' then I get the o/p as the dictionary as I showed below.
{ 1 : {'1': 5, '2': 6, '3': 0} }
{ 2 : {'1': 6, '2': 4, '3': 0} }
{ 3 : {'1': 2, '2': 9, '3': 1} }
I want to convert them to this:
1 1: 5 2: 6 3: 0
2 1: 6 2: 4 3: 0
3 1: 2 2: 9 3: 1
Since dictionary does not have a replace or re.sub method. Its becoming complicated to format them. Also, I cannot convert dict to a string and then do formatting.
for item in [str(k) + " " + "".join(str(k1) + ": " + str(v1) + " " for k1, v1 in v.items()) for k, v in d.items()]:
print item
Upvotes: 0
Views: 92
Reputation: 304365
>>> data = { 1 : {'1': 5, '2': 6, '3': 0},
... 2 : {'1': 6, '2': 4, '3': 0},
... 3 : {'1': 2, '2': 9, '3': 1} }
>>> for k,v in data.items():
... print k, " ".join("{}: {}".format(*i) for i in v.items())
...
1 1: 5 3: 0 2: 6
2 1: 6 3: 0 2: 4
3 1: 2 3: 1 2: 9
Note that neither the order of the lines, or the order of the items on them is preserved, since dict
is unordered
You can easily sort them like this
>>> for k,v in sorted(data.items()):
... print k, " ".join("{}: {}".format(*i) for i in sorted(v.items()))
...
1 1: 5 2: 6 3: 0
2 1: 6 2: 4 3: 0
3 1: 2 2: 9 3: 1
Upvotes: 0
Reputation: 32449
Thefourtheye was faster, but here my version:
d = { 1 : {'1': 5, '2': 6, '3': 0},
2 : {'1': 6, '2': 4, '3': 0},
3 : {'1': 2, '2': 9, '3': 1} }
print('\n'.join('{} {}'.format(k, ' '.join('{}: {}'.format(k, v) for k, v in v.items())) for k, v in d.items()))
inb4: Why is the result not sorted? (standard dicts are never ordered.)
Upvotes: 1