2016-05-17 23 views
2

我正在使用嵌套在列表中的字典編寫程序。我希望在循環列表時打印每個字典的名稱,但不知道如何在不調用字典的全部內容的情況下執行此操作。這裏是我的代碼:如何使用嵌套字典的名稱?

sam = { 
'food' : 'tortas', 
'country' : 'mexico', 
'song' : 'Dream On', 
} 
dave = { 
    'food' : 'spaghetti', 
    'country' : 'USA', 
    'song' : 'Sweet Home Alabama', 
    } 

people = [sam, dave] 

for person in people: 
    for key, value in sorted(person.items()): 
     print(#person's name + 
       "'s favorite " + key + " is " + value + ".") 

這裏是輸出:

's favorite country is mexico. 

's favorite food is tortas. 

's favorite song is Dream On. 

's favorite country is USA. 

's favorite food is spaghetti. 

's favorite song is Sweet Home Alabama. 

一切正常,我只需要我的字典的名稱進行打印。什麼是解決方案?

+2

對象在這個意義上不具有「名稱」。你可以做'bob = dave'之類的東西,然後同一個對象有兩個名字。如果你想要這樣的東西,再加上一層嵌套,把「dave」和「sam」作爲鍵。 – BrenBarn

回答

1

列表中的值實際上不是變量。它們不是通過名稱空間中的某個名稱引用的,而是通過一個整數指示其從列表前面的偏移量(0,1,...)。

如果您想要將每個數據的dict與某個名稱關聯起來,則必須明確地執行此操作。有兩種常規選項,具體取決於負責跟蹤名稱的人員:人員集合或集合中的每個人。

第一個也是最簡單的是collections.OrderedDict ---與正常的dict不同,它將保留列表中的人員的順序。

from collections import OrderedDict 

sam = { 
    'food': 'tortas', 
    'country': 'Mexico', 
    'song': 'Dream On', 
    } 
dave = { 
    'food': 'spaghetti', 
    'country': 'USA', 
    'song': 'Sweet Home Alabama', 
    } 
# The OrderedDict stores each person's name. 
people = OrderedDict([('Sam', sam), ('Dave', dave)]) 

for name, data in people.items(): 
    # Name is a key in the OrderedDict. 
    print('Name: ' + name) 
    for key, value in sorted(data.items()): 
     print(' {0}: {1}'.format(key.title(), value)) 

或者,你可以在他或她自己的dict每個人的姓名存儲......假設你允許更改這些字典的內容。 (另外,你不希望在數據字典中添加任何需要更改/更新數據的東西,因爲大多數人改變他們最喜歡的食物或歌曲的次數比改變他們的名字更頻繁,可能是安全的。)

sam = { 
# Each dict has a new key: 'name'. 
    'name': 'Sam', 
    'food': 'tortas', 
    'country': 'Mexico', 
    'song': 'Dream On', 
    } 
dave = { 
    'name': 'Dave', 
    'food': 'spaghetti', 
    'country': 'USA', 
    'song': 'Sweet Home Alabama', 
    } 
people = [sam, dave] 

for data in people: 
    # Name is a value in the dict. 
    print('Name: ' + data['name']) 
    for key, value in sorted(data.items()): 
     # Have to avoid printing the name again. 
     if 'name' != key: 
      print(' {0}: {1}'.format(key.title(), value)) 

請注意,您如何打印的數據取決於您的收藏(OrderedDict變型中存儲的名稱),或在每個人的dictlist變體)。

3

這樣做的(更)正確的方法是構建dictdict A S代替,如:

people = {'sam': {'food' : 'tortas', 
        'country' : 'mexico', 
        'song' : 'Dream On', 
        }, 
      'dave': {'food' : 'spaghetti', 
        'country' : 'USA', 
        'song' : 'Sweet Home Alabama', 
        } 
      } 

然後,您只需做到以下幾點:

for name, person in people.items(): 
    for key, value in sorted(person.items()): 
     print(name + "'s favorite " + key + " is " + value + ".") 

這將打印以下內容:

dave's favorite country is USA. 
dave's favorite food is spaghetti. 
dave's favorite song is Sweet Home Alabama. 
sam's favorite country is mexico. 
sam's favorite food is tortas. 
sam's favorite song is Dream On. 

作爲便箋,它更易讀使用字符串格式化你的print聲明:

print("{0}'s favorite {1} is {2}".format(name, key, value)) 
2

你基本上試圖做的是打印變量的名稱。當然,這不是可以接受的。如果你真的想這樣做,你應該看看這個帖子: How can you print a variable name in python?

我會做的是將字典的名稱存儲在列表中。你可以通過將'people = [sam,dave]'改爲'people = [[「sam」,sam],[「dave」,dave]]'來做到這一點。這樣,人[0]是人的名字,而人[1]包含該信息。

2

最簡單的方法是名稱存儲爲映射到匹配的變量標識符的字符串:

people = {'sam':sam, 'dave':dave} 

for name, person in people.items(): 
    for key, value in sorted(person.items()): 
     print(name + "'s favorite " + key + " is " + value + ".") 

如果你真的不喜歡打字每名兩次的想法,你可以「內聯」字典:

people = { 
    'sam':{ 
     'food' : 'tortas', 
     'country' : 'mexico', 
     'song' : 'Dream On', 
    }, 
    'dave':{ 
     'food' : 'spaghetti', 
     'country' : 'USA', 
     'song' : 'Sweet Home Alabama', 
    } 
} 

最後,如果你可以依靠這些變量在全局命名空間是與更關心的只是使其比實踐的純度工作,你可以找到他們這樣說:

people = ['sam', 'dave'] 

for name in people: 
    person = globals()[name] 
    for key, value in sorted(person.items()): 
     print(name + "'s favorite " + key + " is " + value + ".") 
0

感謝您的寶貴意見。這個程序是Eric Matthes在「Python Crash Course」中的一個練習例子,所以低效的「列表內的字典」格式是故意的。這就是說,我得到了很多出你的意見,改變了我的代碼,以獲得所需的輸出:

sam = { 
    #Added a 'name' key-value pair. 
    'name' : 'sam', 
    'food' : 'tortas', 
    'country' : 'mexico', 
    'song' : 'Dream On', 
    } 
dave = { 
    'name' : 'dave', 
    'food' : 'spaghetti', 
    'country' : 'USA', 
    'song' : 'Sweet Home Alabama', 
    } 

people = [sam, dave] 

for person in people: 
    for key, value in sorted(person.items()): 
     #Added if statement to prevent printing the name. 
     if key != 'name': 
      print(person['name'].title() + "'s favorite " + key + " is " + value + ".") 
    #Added a blank line at the end of each for loop. 
    print('\n') 

這裏是輸出:再次

Sam's favorite country is mexico. 
Sam's favorite food is tortas. 
Sam's favorite song is Dream On. 


Dave's favorite country is USA. 
Dave's favorite food is spaghetti. 
Dave's favorite song is Sweet Home Alabama. 

謝謝,所有誰提供有見地的答案。