如何从现有密钥设置新密钥:defaultdict的值对?

时间:2017-06-17 00:02:54

标签: python dictionary key list-comprehension defaultdict

我的// Okay, I want to make sure my columns are wide enough for the contents, but I also // Don't want them squished together. So use resizeColumnToContents, to make them // as small as they can be to show the contents, then take those widths and add some // spacing and then set the columns to the new widths. m_tree->resizeColumnToContents (0); m_tree->resizeColumnToContents (1); int w0 = m_tree->columnWidth (0) + 20; int w1 = m_tree->columnWidth (1) + 20; m_tree->setColumnWidth (0, w0); m_tree->setColumnWidth (1, w1); 值为:

defaultdict(dict)

说,我想以defaultdict(<class 'dict'>, { 'AL2G22360.t1_Sp': { 'locus': 'AL2G22360.t1', 'length': '663', 'strain': 'Sp'}, 'AL2G22360.t1_My': { 'locus': 'AL2G22360.t1', 'length': '389', 'strain': 'My'}, 'AL2G22220.t1_My': { 'locus': 'AL2G22220.t1', 'length': '865', 'strain': 'My'}, 'AL2G22220.t1_My': { 'locus': 'AL2G22220.t1', 'length': '553', 'strain': 'My' ........}}) major key的方式进行更改。由于value of variable **locus**有一个副本(非唯一,但有些可能是唯一的),我希望从locus value获得另一个子密钥My vs. Sp。其余数据可以保持原样。

预期产出:

variable **strain**

1 个答案:

答案 0 :(得分:1)

我会这样做:

result = defaultdict(lambda: defaultdict(dict))
for k, v in a.items():
  result[v['locus']][v['strain']] = { 'keys': k, 'length': v['length'] }
return result

这会创建一个defaultdict,其值也是默认值,其值为dicts。 (这与您指定的输出匹配。)然后通过迭代原始并将所有值复制到新格式,以直接的方式填充。