2013-09-24 39 views
3

我有一個n元組的字典。我想從這個包含特定鍵值對的元組中檢索一個字典。使用Python list-comprehension從嵌套元組字典結構中檢索數據

我試圖儘可能優雅地做到這一點,我認爲列表理解是要走的路 - 但這不是一個基本的列表理解,我有點失落。

這說明了什麼,我試圖做的想法,但它並沒有當然的工作:

# 'data' is my n-tuple 
# 'myKey' is the key I want 
# 'myValue is the value I want 

result = [data[x] for dictionary in data if (data[x][myKey]) == myValue)][0] 

# which gives this error: 

NameError: global name 'x' is not defined 

之前,我是想這樣的事情(錯誤有意義,我的理解):

result = [data[x] for x in data if (data[x][myKey] == myValue)][0] 

# which gives this error: 

TypeError: tuple indices must be integers, not dict 

這是使用嵌套解析的時候嗎?那看起來會是什麼樣子,在這一點上用循環和條件寫出來會更簡單嗎?

此外,側面的問題 - 是否有一種更pythonic的方式來獲得列表中的第一個(或唯一的)元素,除了最後只是抨擊[0]?

回答

1

如果你有字典稱爲數據的元組,你可以這樣做:

>>> data = ({'fruit': 'orange', 'vegetable':'lettuce'}, {'football':'arsenal', 'basketball':'lakers'}, {'england':'london', 'france':'paris'}) 
>>> myKey = "football" 
>>> myValue = "arsenal" 
>>> [d for d in data if (myKey, myValue) in d.items()][0] 
{'basketball': 'lakers', 'football': 'arsenal'} 

這將返回第一庫的元組包含myKeymyValue使用列表理解(刪除[0]獲取所有字典)。

2

最Python的方式是使用next()

通過調用next()方法檢索迭代器的下一個項目。 如果給出默認值,則在迭代器用盡時返回,否則返回StopIteration。 。

data = ({'1': 'test1'}, {'2': 'test2'}, {'3': 'test3'}) 
myKey = '2' 
myValue = 'test2' 

print next(x for x in data if x.get(myKey) == myValue) # prints {'2': 'test2'} 

您也可以在指定的情況下,項目沒有發現默認值:

myKey = 'illegal_key' 
myValue = 'illegal_value' 

print next((x for x in data if x.get(myKey) == myValue), 
      'No item found') # prints "No item found" 
+0

如果以這種方式定義元組數據,我將如何解決這個問題data =({「one」:'I','three':'III','five':'V'},{「兩個「:'II','four':'IV'})'和myKey ='one',myValue ='I' – kvivek

+0

@kvivek,它起作用,因爲OP詢問:'我想從字典中檢索字典這個包含特定鍵值對的元組' – alecxe

+0

我不明白爲什麼@ kvivek的情況是一個問題;當我測試它時,你的方法就能處理它。也許他誤解了我的問題? 這個答案符合我的需求,但它需要讀者理解發生器 - 我沒有在我的代碼中使用任何其他地方。爲了保持一致,我將與jabaldonedo的答案一致。 –

1

但爲什麼接下來呢? 只需使用發生器。我會做這樣的(有點改變了代碼alecxe):

data = ({'1': 'test1'}, {'2': 'test2'}, {'3': 'test3'}) 
myKey = '2' 
myValue = 'test2' 

result = [data[x] for x in data if data[x] == myValue]