0

INPUT:

`videoshop=[]

for i in range(0,3,1):
    movie={}
    print("Enter Movie Name")
    movie["Name"]=raw_input("Enter Here: ")
    print("Enter Movie Duration")
    movie["Duration"]=raw_input("Enter Here: ")
    print("Enter Movie Age")
    movie["Age"]=raw_input("Enter Here: ")
    print("Enter Movie Price")
    movie["Price"]=raw_input("Enter Here: ")

    videoshop.append(movie)


print(videoshop)`

OUTPUT

    `[{'Duration': '51', 'Age': '16+', 'Name': 'Jeff', 'Price': '$99'}, {'Duration': 
'52', 'Age': '14', 'Name': 'Darm', 'Price': '$99'}, {'Duration': '56', 'Age': '18+', 
'Name': 'Shaw', 'Price': '$102'}]`

QUESTION

I need the output to show [{'name':'jeff','Duration':'51', 'Age':'16+','Price':'$99'}] I have tried sorting the objects but it has failed with this code...

EnderShadow8
  • 788
  • 6
  • 17
  • What field do you want to sort the list on? Age? Price? Duration? – scotty3785 Feb 25 '21 at 11:50
  • How did you try sorting the objects? Python has a `sorted` function that takes a lambda. See https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – mmohammad Feb 25 '21 at 21:52
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – mmohammad Feb 25 '21 at 21:52

1 Answers1

0

The python sorted function is very powerful for sorting items.

The below example will sort the items in the list by price. The key attribute passed to sorted tells what value it should sort by. In this case, I strip the $ from the start of the price, convert it to an integer and sort it by that.

videoshop = [{'Duration': '51', 'Age': '16+', 'Name': 'Jeff', 'Price': '$99'}, {'Duration': 
'52', 'Age': '14', 'Name': 'Darm', 'Price': '$99'}, {'Duration': '56', 'Age': '18+', 
'Name': 'Shaw', 'Price': '$102'}]

by_price = sorted(videoshop, key=lambda x: int(x['Price'].replace('$','')))

To sort by duration, the idea is the same, except we just convert the duration to an integer.

by_duration = sorted(videoshop, key=lambda x: int(x['Duration']))

If you want to sort the fields as they appear in the dictionary, you'll need to use an ordered dictionary as normal dictionary keys are unordered. Below snippet shows how you can create an ordered dictionary with your required keys.

from collections import OrderedDict

for i in range(0,3,1):
    movie = OrderedDict.fromkeys(['Name','Duration','Age','Price'])
scotty3785
  • 6,763
  • 1
  • 25
  • 35