Python Forum
Input validation for nested dict and sorting list of tuples
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Input validation for nested dict and sorting list of tuples
#1
Hi everyone,
First of all I want to say that I really appreciate this forum and Ive learned alot since I joined!
Im trying to write a func that icludes input validation for a nested dict, converting it to a list of tupples and then arrange it by order.

this is the nested dict:
{'Afghanistan': {'Gold': 0, 'Silver': 0, 'Bronze': 2, 'Total': 2}, 'Albania': {'Gold': 0, 'Silver': 0, 'Bronze': 0, 'Total': 0}, 'Algeria': {'Gold': 5, 'Silver': 4, 'Bronze': 8, 'Total': 17}}
this is the output I want to get in the end:
Output:
[(' 1 , ‘Algeria’, 17), (2, 'Afghanistan, 2), (3, ‘Albania, 0)[
Thats my try:
def rank_countries(dict1):
    if isinstance(dict1, dict):
         for i in dict1:
             if isinstance(dict1[i], dict):
                 new_list = [(k, v['Total']) for k, v in dict1.items()]
                 new_list=sorted(new_list, key= lambda tup: tup[1], reverse= True)   
                 return new_list
                     
                        
    else:
       return 'Input must be a nested dictionary.'
which give me this output:
Output:
[(' ‘Algeria’, 17), ('Afghanistan, 2), ( ‘Albania, 0)[
So I get the ordeer I want but I dont know how to add the digits in start of each tuple that declair the rank of the country... also Im not sure in my input validation for the nested dicionary is good or its only right for the first dictionary..

Thanks for any kind of help!
Reply


Messages In This Thread
Input validation for nested dict and sorting list of tuples - by ranbarr - May-13-2021, 03:14 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Homework - List containing tuples containing dicti Men 4 2,142 Dec-28-2021, 12:37 AM
Last Post: Men
  sorting a list using unicodes acending order, no loops, no sort(), using recursion lrn2codee 14 6,675 Jun-23-2021, 07:33 PM
Last Post: deanhystad
  Sorting list - Homework assigment ranbarr 1 2,308 May-16-2021, 04:45 PM
Last Post: Yoriz
  Removing existing tuples from a list of tuple Bruizeh 4 2,908 May-15-2021, 07:14 PM
Last Post: deanhystad
  List index out of range when turning CSV into dict ranbarr 15 6,779 May-12-2021, 10:38 AM
Last Post: ranbarr
  nested looping with list cap510 2 1,977 Sep-10-2020, 04:51 AM
Last Post: cap510
  Sorting nested lists in ascending order jszum 2 2,348 May-17-2020, 01:35 PM
Last Post: jefsummers
  how to add the user input from file into list wilson20 8 4,436 May-03-2020, 10:52 PM
Last Post: Larz60+
  Python Adding +1 to a list item cointained in a dict ElReyZero 1 2,137 Apr-30-2020, 05:12 AM
Last Post: deanhystad
  Dict from list - HELP! PLEASE! cherry_cherry 16 5,841 Apr-09-2020, 04:01 AM
Last Post: cherry_cherry

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020