【问题标题】:Splitting a python dict from a certain key从某个键中拆分 python dict
【发布时间】:2013-05-14 13:23:32
【问题描述】:

我正在尝试从字典中的某个点拆分字典。似乎做一个简单的items_dict[3:] 会起作用,但它不起作用。

items_dict = {
    "Cannon barrels":10,
    "Cannon furnace":12,
    "Candle":36,
    "Bronze arrowheads":39,
    "Iron arrowheads":40,
    "Steel arrowheads":41,
    "Mithril arrowheads":42,
    "Adamant arrowheads":4
}
print items_dict[3:] # Nope, this won't work
print items_dict["Candle"] # This will of course, but only returns the Candle's number

我只知道如何to slice a dictionary by keys that start with a certain string,但我只是想知道如何将一个类似于列表的字典切片。

【问题讨论】:

  • 看起来你应该重新考虑你的数据结构。我认为在这里使用 OrderedDict 不是一个好主意。

标签: python dictionary slice


【解决方案1】:

字典没有顺序,所以你不能从某个点拆分它。查看那里的字典,您无法提前知道第一个元素是什么。

【讨论】:

    【解决方案2】:

    如果您想在 n 个键后拆分 - 无法保证顺序。

    n=3
    d1 = {key: value for i, (key, value) in enumerate(d.items()) if i < n}
    d2 = {key: value for i, (key, value) in enumerate(d.items()) if i >= n}
    

    【讨论】:

    • viewitems 是 python2.7。 items 将适用于 python2 或 python3。
    • 你也可以这样做:{k:d[k] for k in islice(d,...)}
    • 按照下面的答案和上面的评论中的建议使用 OrderedDict,这可以根据需要进行!
    • @mgilson,islice 要好得多,但使用iter(d),这样您就可以避免多次循环播放内容。
    • @gnibbler -- 抱歉,你需要再带我看一遍。使用islice 是如何导致你循环多次的?
    【解决方案3】:

    如果您想要一个按顺序存储键的字典,请使用collections.OrderedDict

    http://docs.python.org/2/library/collections.html#collections.OrderedDict

    【讨论】:

      【解决方案4】:
      items = [
          ("Cannon barrels",10),
          ("Cannon furnace",12),
          ("Candle",36),
          ....
         ]
      
      items_dict = dict(items)
      
      items_3_dict = dict(items[3:])
      

      没有准确回答您的问题(请参阅@mgilson 答案),但提供了前进的道路

      【讨论】:

        【解决方案5】:
        ditems = items_dict.items()
        d1, d2 = dict(ditems[:3]), dict(ditems[3:])
        
        print(d1)
        print(d2)
        {'Iron arrowheads': 40, 'Adamant arrowheads': 4, 'Mithril arrowheads': 42}
        {'Candle': 36, 'Cannon barrels': 10, 'Steel arrowheads': 41, 'Cannon furnace': 12, 'Bronze arrowheads': 39}
        

        或者创建一个函数来拆分一个关于 n-th 值的迭代

        from itertools import islice
        
        def split(iterable,point): 
            return islice(iterable,None,point), islice(iterable,point,None)
        
        d1, d2 = (dict(segment) for segment in split(items_dict.items(),3))
        

        这将拆分第三个​​条目。

        【讨论】:

        • 不,它不会......一个字典没有“第三个条目”的概念......它会创建一个包含 3 个项目的字典和另一个包含其余项目的字典......但是没有“第三项”的概念
        • @JoranBeasley(是的,它是无序的)但它仍然有 N (k,v) 对,我的意思是输入,所以即使第三对不确定,它仍然有第三对。
        【解决方案6】:

        您可以创建一个自定义类(仅示例 - 切片仅适用于 [1:4] 语法,dict[missing_key] 返回 None 而不是抛出异常):

        >>> class SliceDict(collections.OrderedDict):
        ...     def __getitem__(self, val):
        ...         if isinstance(val, slice):
        ...             return {key: value for i, (key, value) in enumerate(d.items()) if val.start < i < val.stop}
        ...         else:
        ...             return self.get(val)
        

        现在我们可以添加您的项目字典:

        >>> d = SliceDict(items_dict)
        SliceDict([('Adamant arrowheads', 4), ('Mithril arrowheads', 42), ('Iron arrowheads', 40), ('Candle', 36), ('Cannon barrels', 10), ('Steel arrowheads', 41), ('Cannon furnace', 12), ('Bronze arrowheads', 39)])
        >>> d[1:5]
        {'Candle': 36, 'Cannon barrels': 10, 'Iron arrowheads': 40}
        >>> d['Candle']
        36
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-05
          • 1970-01-01
          • 2019-08-08
          • 2012-01-16
          • 2016-03-14
          • 2019-09-22
          • 1970-01-01
          • 2017-09-16
          相关资源
          最近更新 更多