python:排序3级嵌套字典

时间:2016-01-21 16:41:39

标签: python dictionary

我的字典看起来像:

     {modID1:{sequences1:{header1:count1},sequences2:{header2:count2}...},
      modID2:{sequences1:{header1:count1},sequences2:{header2:count2}...}....}

我想反向排序"序列"通过" count", 示例:

{modID1:
    {sequences1:{header1: 3},sequences2:{header2:5},
     sequences3:  {header3:1}...},
modID2:{sequences1:{header1:1},sequences2:{header2:8},...},
....}

通缉输出:

{modID1:
  {sequences2:{header2:5},sequences1:{header1: 3},
   sequences3:{header3:1}...},
modID2:{sequences2:{header2:8},sequences1:{header1:1},...},
....}

我已经看过一些帖子了,我试图使用类似的东西:

 for k,v in Dic.iteritems():
    sorted=OrderedDict(sorted(v.iteritems(), key=lambda h: v[seq for seq in v][header], reverse=True))

但我想我并没有完全使用这个功能,所以不能正常工作。建议?

提前谢谢

2 个答案:

答案 0 :(得分:0)

假设你不关心外部词典的顺序,只关心序列的内部序列,那么你可以这样做:

>>> from collections import OrderedDict
>>> data = {'modID1': {'sequences2':{'header2':5}, 'sequences1':{'header1': 3},
...                    'sequences3':{'header3':1}},
...         'modID2': {'sequences2':{'header2':8},'sequences1':{'header1': 1}}}
>>> {k: OrderedDict(sorted(v.items(), key=lambda x: -sum(x[1].values()))) 
...  for k, v in data.items()}
{'modID1': OrderedDict([('sequences2', {'header2': 5}), ('sequences1', {'header1': 3}),
                        ('sequences3', {'header3': 1})]),
 'modID2': OrderedDict([('sequences2', {'header2': 8}), ('sequences1', {'header1': 1})])}

答案 1 :(得分:0)

python 3的例子

lambda h: v[seq for seq in v][header]

输出

lambda h: next(iter(h[1].values())

我将lambda函数从h更改为("sequences", {"header": count})

  1. h[1]{"header": count}
  2. next(iter(h[1].values()){"header": count}
  3. count {“header”:count} getting first value of dict
  4. 的第一个值
  5. items()的第一个值是iteritems()
  6. 在python 3中{p> .*\|([A-Za-z]+) 的工作方式与.*\|([A-Za-z]+)(\d+) dict.items() and dict.iteritems()

    类似