I have a code in which I need to sort the elements of my dictionary in my main list using a function I define with two parameters. The first parameter is my list with dictionaries and the second one has to be a boolean set to True by default. I want my output to be the sorted list of sorted countries the authors are from if I only write "get_diff_countries(list_authors)" and the output of not sorted countries if I call "get_diff_countries(list_authors, False)". Here is my code so far:
### Part 1
list_authors = [{'author_id' : 1, 'fullname': 'Jenine Thomson', 'age' : 58, 'country' : 'Ecuador', 'continent' : 'South America'},
{'author_id' : 2, 'fullname': 'Lavonna Mayberry', 'age' : 92, 'country' : 'France', 'continent' : 'Europe'},
{'author_id' : 3, 'fullname': 'Lewis Strain', 'age' : 29, 'country' : 'Korea (Republic of)', 'continent' : 'asia'}, ...]
list_books = [{'id': 1, 'title': 'The Fractured Birds', 'genre': 'Crime', 'nberPages': 500, 'price': 316.00, 'author_id': 20},
{'id': 2, 'title': 'Solar Eclipse of the Heart', 'genre': 'Romance', 'nberPages': 444, 'price': 204.00, 'author_id': 5},
{'id': 3, 'title': 'The dark maid', 'genre': 'Mystery', 'nberPages': 277, 'price': 65.00, 'author_id': 8}, ...]
### Part 2
def get_diff_countries(alist, sorted=True):
list1 = []
for dict in alist:
list1.append(dict['country'])
return list1
print(get_diff_countries(list_authors))
CodePudding user response:
You can firstly convert this into a pandas
dataframe and then sort the dataframe by the country
column.
import pandas as pd
df = pd.DataFrame(list_authors)
sorted_df = df.sort_values(by = "country")
To get the dataframe in a dictionary do this,
df_values = sorted_df.values
list(map(lambda row: dict(zip(df.columns, row)), df_values))
This would return the sorted dictionary you desire.
To write this all in a function do this,
def get_diff_countries(alist, sorted = True):
df = pd.DataFrame(alist)
df_values = df.sort_values(by = "country", ascending = sorted).values
return list(map(lambda row: dict(zip(df.columns, row)), df_values))
CodePudding user response:
Does this what you want to do:
def get_diff_countries(alist, sort=True):
countries = (record["country"] for record in alist)
return sorted(countries) if sort else list(countries)
I wouldn't use sorted
as variable name because this overwrites access to the built-in function sorted()
, which is useful here.