python使用dict理解按项拾取和删除

python使用dict理解按项拾取和删除,python,dictionary,Python,Dictionary,如果我有下面这本词典,最好的方法是什么 选择具有部分键的所有项目1d 然后根据该键删除这些项 c={('1d','f1'):1.5,('1w','f1'):1.2,('1d','f2'):1.4} 谢谢 对于一般情况,如果k中没有“1d”,则使用。在Python2.x中,使用dict.iteritems(迭代器而不是列表) 在py2.x中,使用c.iteritems()返回迭代器,对于py3.x,可以使用c.items() >注意 C项()/CUT>将在两个版本中工作。 < P>请考虑以下方法

如果我有下面这本词典,最好的方法是什么

  • 选择具有部分键的所有项目
    1d
  • 然后根据该键删除这些项

    c={('1d','f1'):1.5,('1w','f1'):1.2,('1d','f2'):1.4}

  • 谢谢

    对于一般情况,如果k中没有“1d”,则使用
    。在Python2.x中,使用
    dict.iteritems
    (迭代器而不是列表)

    在py2.x中,使用
    c.iteritems()
    返回迭代器,对于py3.x,可以使用
    c.items()


    <> >注意<代码> C项()/CUT>将在两个版本中工作。

    < P>请考虑以下方法< /P> 在Python2.7及更高版本中,您可以使用dict comprehension

    >>> c = {('1d','f1'):1.5,('1w','f1'):1.2,('1d','f2'):1.4}
    >>> {k: v for k, v in c.items() if '1d' not in k}
    {('1w', 'f1'): 1.2}
    
    在Python2.6和更低版本中,应该使用generator代替dict

    >>> c = {('1d','f1'):1.5,('1w','f1'):1.2,('1d','f2'):1.4}
    >>> dict((k, v) for k, v in c.iteritems() if '1d' not in k)
    {('1w', 'f1'): 1.2}
    

    谢谢@jamylak。这正是我想要的。我们可以在这里使用
    iteritems()
    来获得内存效率高的解决方案。@AshwiniChaudhary没有提到Python版本,所以我选择了一个交叉兼容的解决方案
    >>> c = {('1d','f1'):1.5,('1w','f1'):1.2,('1d','f2'):1.4}
    >>> {k: v for k, v in c.items() if '1d' not in k}
    {('1w', 'f1'): 1.2}
    
    >>> c = {('1d','f1'):1.5,('1w','f1'):1.2,('1d','f2'):1.4}
    >>> dict((k, v) for k, v in c.iteritems() if '1d' not in k)
    {('1w', 'f1'): 1.2}