0

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
4

2 回答 2

1

Thefourtheye 更快,但这里是我的版本:

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:为什么结果没有排序?(从不订购标准字典。)

于 2013-11-07T02:31:54.937 回答
0
>>> 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

请注意,行的顺序或它们上的项目的顺序都没有保留,因为dict它是无序的

您可以像这样轻松地对它们进行排序

>>> 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
于 2013-11-07T02:36:22.403 回答