2017-04-12 104 views
-1

所以特定值當我打印詞典將其給出:獲取在Python嵌套字典

u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'}, {u'Value': 'hello world', u'Key': 'Name'}, {u'Value': '123 Street', u'Key': 'Address'}] 

我需要重點「名稱」的價值,即「世界,你好」

我嘗試這樣做:

for t in Tags: 
    print(t["Name"]) 

,但得到的錯誤:

KeyError: 'Name' 
+1

'Name'是價值!你必須使用密鑰 – RaminNietzsche

+0

u'Value':'hello world' - > t ['Value']會給你。這是使用名稱wronf –

回答

1

'Name'這裏不是關鍵,它是一個值。你的字典都有鑰匙u'Key'u'Value'這可能會有點混淆。

這應該爲你的榜樣的工作,雖然:

for t in Tags: 
    if t['Key'] == 'Name': 
     print t['Value'] 
2

在字典中,條目Tags指向具有鍵和值的對象列表作爲嵌套條目。因此,訪問不是直接的,需要搜索密鑰。如果你想找到一個「鍵名」

d = {u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'}, 
       {u'Value': 'hello world', u'Key': 'Name'}, 
       {u'Value': '123 Street', u'Key': 'Address'}]} 

name = next((v for v in d['Tags'] if v['Key'] == 'Name'), {}).get('Value') 
0

findYourWord ='hello world' 

for dictB in dictA[u'Tags']: 
    for key in dictB: 
     if dictB[key]== findYourWord: 
      print(key) 

希望這有助於你可以使用一個簡單的列表理解來完成。祝你今天愉快。

0

在你內心的字典,唯一鍵「鍵」和「值」。儘量讓一個函數來找到你想要的關鍵字的值,請嘗試:

def find_value(list_to_search, tag_to_find): 
    for inner_dict in list_to_search: 
     if inner_dict['Key'] == tag_to_find: 
      return inner_dict['Value'] 

現在:

In [1]: my_dict = {u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'}, {u'Value': 'hello world', u'Key': 'Name'}, {u'Value': '123 Street', u'Key': 'Address'}]} 


In [2]: find_value(my_dict['Tags'], 'Name') 
Out[2]: 'hello world'