2013-05-20 65 views
1

我試圖從字典中的某個點拆分字典。這似乎是做一個簡單的items_dict[3:]將工作,但它沒有奏效。從某個鍵分割一個python字典

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,但我只是想知道怎麼給字典類似於列表。

+2

看起來也許你應該重新考慮你的數據結構。我認爲在這裏使用OrderedDict並不是一個好主意。 –

回答

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} 
+1

這仍然沒有給他任何控制哪3個鍵... –

+0

'viewitems'是python2.7。 'items'將在python2或python3上運行。 – mgilson

+0

你也可以這樣做:'{k:d [k] for k in islice(d,...)}' – mgilson

4

字典沒有順序,所以你不能從某個特定點分割它。看看你在那裏的字典,你不能提前知道第一個元素是什麼。

1
items = [ 
    ("Cannon barrels",10), 
    ("Cannon furnace",12), 
    ("Candle",36), 
    .... 
    ] 

items_dict = dict(items) 

items_3_dict = dict(items[3:]) 

犯規準確回答你的問題(見@mgilson答案),但提供了前進

1
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個值

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)) 

這將可迭代的分裂它有關的第三項。

+0

不,它不會......字典沒有「第三條目」的概念......它將創建一個與3個項目和另一個字典與其餘的字典。 ..但沒有「第三條目」的概念 –

+0

@JoranBeasley(是的,它是無序的)但它仍然有N(k,v)對,我的意思是進入,所以即使第三對不確定它仍然有第三對。 – HennyH

0

你可以做一個自定義類(唯一的例子 - 切片僅適用於[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 
相關問題