【问题标题】:Accessing multiple dictionary values访问多个字典值
【发布时间】:2013-04-09 07:03:32
【问题描述】:

我有两个格式如下的字典

    d=defaultdict(<class 'collections.OrderedDict'>, {u'1': OrderedDict([(1746L, 1), (2239L, 1)]), u'2': OrderedDict([(1965L, 2)]),u'3': OrderedDict([(2425L, 1),(2056L, 4)])})  

    e={2056L: 3, 1746L: 3, 2239L: 2, 1965L: 3, 2425L: 4}

我怎样才能创建另一个这种格式的字典??

    {u'1':{1746L:(1,3),2239L:(1,2)},u'2':{1965L:(2,3)},u'3':{2425L:(1,4),2056L(4,3)}}

【问题讨论】:

    标签: python dictionary ordereddictionary


    【解决方案1】:
    >>> {i: {j: (d[i][j], e[j]) for j in d[i]} for i in d}
    {u'1': {1746L: (1, 3), 2239L: (1, 2)}, u'3': {2056L: (4, 3), 2425L: (1, 4)}, u'2': {1965L: (2, 3)}}
    

    【讨论】:

    • 哦,我明白了。在那种情况下,也许只是做for j in d[i] if j in e
    • {i:{j:(d[i][j],e[j]) for j in d[i] if j in e}for i in d} 在同一代码中如何我可以删除所有具有空值的字典
    猜你喜欢
    • 2021-05-09
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2020-12-13
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多