【问题标题】:Dictionary comprehension within a list comprehension, per dictionary in other list列表理解中的字典理解,其他列表中的每个字典
【发布时间】:2016-11-09 02:02:46
【问题描述】:

我正在尝试创建一个字典列表,其中列表中的字典是从预先存在的字典列表创建的,为此应该从每个字典的键值对的聚合中创建一个新字典字典的预先存在的列表,如果键是另一个预先存在的列表 (child_container) 的成员。

或者换句话说,我试图在字典列表 (child_container) 中过滤掉字典 (d) 中不属于 list_multiple_tagnames 成员的键。

[d for d in child_container if isinstance(d, dict) for k, v in d.iteritems() if k in lst_multiple_tagnames]

预期的效果是在 child_container 中创建一个字典 PER 字典 d,只有 lst_multiple_tagnames 中的键值对。

【问题讨论】:

    标签: python list-comprehension dictionary-comprehension


    【解决方案1】:

    必须使用 dict 理解,复合 for 不捕获 per-key-per-dictionary 范围。

    [{k:v for k,v in d.iteritems() if k in lst_multiple_tagnames} for d in child_container if isinstance(d, dict)]
    

    【讨论】:

      【解决方案2】:
      assume child_container = [{ 1:1,3:324,2:2334}, {1:123},{2:2}]
      for d in child_container:
      ...     if isinstance(d,dict):
      ...         for k in d:
      ...             res[k] = res.get(k,[]) + [d[k]]
      print res
      {1: [1, 123], 2: [2334, 2], 3: [324]}
      

      【讨论】:

        猜你喜欢
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 2018-03-18
        相关资源
        最近更新 更多