2016-03-25 41 views
1

嵌套字典的Python越來越按鍵和Max我有字典是這樣的的價值

d = { address { 'Avenue' : 3000, 
       'Street' : 3000, 
       'road' : 4000}, 
     movieprice { 
        'panda' : 40, 
        'fastandfurious' : 30, 
        'starwars': 50}} 

我想出來把這樣的事情

address Avenue,Street,road 4000 ---> last Column should max of values max(3000,3000,4000) 
movie panda,fastandfurious,starwars 50 --> max of value. 

任何幫助表示讚賞。

+2

你'D'是不是有效的Python字典。你到目前爲止嘗試過什麼? – Selcuk

+0

如何按值排序字典:http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value希望這可以幫助 – Thiru

回答

1

這個怎麼樣(假設我們解決您的字典):

d = {'address': {'Avenue': 3000, 
       'Street': 3000, 
       'road': 4000}, 
    'movieprice': {'panda': 40, 
        'fastandfurious': 30, 
        'starwars': 50}} 

for k, nested in d.items(): 
    print("%s %s, %d" % (k, ', '.join(nested.keys()), max(nested.values()))) 

打印:

address Street, road, Avenue, 4000 
movieprice panda, fastandfurious, starwars, 50 
+0

謝謝你們的幫助。我糾正了我的字典。 – Ram

0

要查找字典的最大值,你可以做

d = some_dictionary 
max(d.values()) 

這會給你最大的價值。至於發現哪些鍵具有最大值,您必須遍歷字典鍵並針對max(d.values())進行測試,因爲多個鍵可能具有相同的值。所以它會是這樣的

d = some_dictionary 
max_value_keys = [d[x] for x in d.keys if d[x] == max(d.values())] 
0

首先,你需要讓你的字典有效。如果將它嵌套在另一個字典中,則必須將每個字典定義爲鍵值對的值。下面是正確的代碼:

d = { 'address' : { 'Avenue' : 3000, 
      'Street' : 3000, 
      'road' : 4000}, 
     'movieprice' : { 
       'panda' : 40, 
       'fastandfurious' : 30, 
       'starwars': 50}} 

從那裏,你可以通過字典使用呸的解決方案,以循環和打印他們的密鑰和值的最大值。

0

排序字典和打印值

import operator 
d = {} # your nested dictonary 
for k, nested in d.items(): 
    print k, ",".join([item[0] for item in sorted(nested.items(), key=operator.itemgetter(0))]), max(nested.values()) 

輸出:

movieprice fastandfurious,panda,starwars 50 
address Avenue,Street,road 4000 
0

嘗試以下操作:

for i in d: 
    print i, ','.join(d[i].keys()), max(d[i].values()) 

>>> for i in d: 
...  print i, ','.join(d[i].keys()), max(d[i].values()) 
... 
movieprice starwars,panda,fastandfurious 50 
address Street,Avenue,road 4000 
>>>