【问题标题】:Extracting key/value pair from dictionary从字典中提取键/值对
【发布时间】:2013-06-09 04:13:53
【问题描述】:

好的,这是一个 Python 问题:

我们有一本字典:

my_dict = {
           ('John', 'Cell3', 5): 0, 
           ('Mike', 'Cell2', 6): 1, 
           ('Peter', 'Cell1', 6): 0, 
           ('John', 'Cell1', 4): 5, 
           ('Mike', 'Cell2', 1): 4, 
           ('Peter', 'Cell1', 8): 9
          }

你如何制作另一个字典,它只包含名称为“Peter”的键/值对?

如果你把这本字典变成一个元组的元组列表会有帮助吗,by

tupled = my_dict.items()

然后再转回字典?

你如何用列表理解来解决这个问题?

提前致谢!

【问题讨论】:

    标签: python list dictionary tuples


    【解决方案1】:

    试试这个,使用 Python 2.7 或更新版本中的dictionary comprehensions

    { k:v for k,v in my_dict.items() if 'Peter' in k }
    

    或者,如果我们确定名称将始终位于第一位,我们可以这样做,这会更快一些:

    { k:v for k,v in my_dict.items() if k[0] == 'Peter' }
    

    如果您使用的是旧版本的 Python,我们可以使用生成器表达式和 dict() 构造函数的正确参数获得等效结果:

    dict((k,v) for k,v in my_dict.items() if k[0] == 'Peter')
    

    不管怎样,结果如预期:

    => {('Peter', 'Cell1', 8): 8, ('Peter', 'Cell1', 6): 0}
    

    【讨论】:

      【解决方案2】:
      {item for item in my_dict.iteritems() if item[0][0].lower() == 'peter'}
      

      .iteritems 遍历字典,我们使用 .lower 进行匹配,不区分大小写。

      【讨论】:

        【解决方案3】:

        任何名字

        def select(d, name):
            xs = {}
            for e in d:
                if e[0].lower() == name.lower(): xs[e] = d[e]
        
            return xs
        
        d = {('Alice', 'Cell3', 3): 9,
             ('Bob', 'Cell2', 6): 8,
             ('Peter', 'Cell1', 6): 0,
             ('Alice', 'Cell1', 6): 4,
             ('Bob', 'Cell2', 0): 4,
             ('Peter', 'Cell1', 8): 8
            }
        
        print select(d, 'peter')
        
        >>>{('Peter', 'Cell1', 8): 8, ('Peter', 'Cell1', 6): 0}
        

        【讨论】:

          猜你喜欢
          • 2019-10-04
          • 1970-01-01
          • 2011-07-18
          • 1970-01-01
          • 2016-06-24
          • 1970-01-01
          • 1970-01-01
          • 2014-12-06
          相关资源
          最近更新 更多