0

I have dict something like this

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

I want out put something like this

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

Any help appreciated.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Ram
  • 9
  • 2
  • 2
    Your `d` is not a valid Python dictionary. And what have you tried so far? – Selcuk Mar 25 '16 at 05:22
  • how to sort dict by value: http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value hope this helps – Thiru Mar 25 '16 at 05:35

5 Answers5

1

What about this (assuming we fix your dictionary):

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

Prints:

address Street, road, Avenue, 4000
movieprice panda, fastandfurious, starwars, 50
Bahrom
  • 4,752
  • 32
  • 41
0

To find the maximum value of a dictionary you can just do

d = some_dictionary
max(d.values())

That will give you the maximum value. As for finding which keys have that max value you'd have to iterate through the dictionary keys and test against max(d.values()) because multiple keys could have the same value. So it'd be something like so

d = some_dictionary
max_value_keys = [d[x] for x in d.keys if d[x] == max(d.values())]
Luis F Hernandez
  • 891
  • 2
  • 14
  • 29
0

First, you need to make your dictionary valid. If you're nesting it inside another dictionary, you have to define each dictionary as a value of a key-value pair. Here is the correct code:

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

From there, you can use Bah's solution to loop through the dictionaries and print their keys and the max of their values.

Rohan
  • 482
  • 6
  • 16
0

Sort the dictionary and print the values

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

output:

movieprice fastandfurious,panda,starwars 50
address Avenue,Street,road 4000
Thiru
  • 3,293
  • 7
  • 35
  • 52
0

Try the following:

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
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76