Python Forum
Convert all actions through functions, fill the dictionary from a file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert all actions through functions, fill the dictionary from a file
#1
I can't figure out how to make functions for the dictionary in the dictionary, how to pass arguments if there is a string. It would be nice if someone could write at least one function, then I would understand the progress of the task and I think I could finish the rest. Thanks in advance!
Here is the code for which I need to do all these tasks:

my_dict={'1':{'surname':'Musk', 'name':'Elon', 'gender': 'm','growth':183},
'2':{'surname':'Holmes', 'name':'Enola', 'gender': 'f','growth':175},
'3':{'surname':'Brown', 'name':'Lilly', 'gender': 'f','growth':178},
'4':{'surname':'Lothbrok', 'name':'Ragnar', 'gender': 'm','growth':189},
'5':{'surname':'Smith', 'name':'Adreana', 'gender': 'f','growth':173},
'6':{'surname':'Moon', 'name':'Larry', 'gender': 'm','growth':184}}
for key in my_dict:
if my_dict[key]['gender']=='m':
male_max_growth = max(my_dict.keys(), key=(lambda key: my_dict[key]['growth']))
tallest_guy=my_dict[male_max_growth]['surname']
print('The tallest guy: ', tallest_guy)

for key in my_dict:
if my_dict[key]['gender']=='f':
female_min_growth = min(my_dict.keys(), key=(lambda key: my_dict[key]['growth']))
lowest_girl=my_dict[female_min_growth]['surname']
print('The lowest girl: ', lowest_girl)

for key in my_dict:
sorted_key=sorted(my_dict.keys(), key=(lambda key: my_dict[key]['surname']))
for i in sorted_key:
student1=sorted_key[0]
student2=sorted_key[1]
student3=sorted_key[2]
student4=sorted_key[3]
student5=sorted_key[4]
student6=sorted_key[5]
print('Information about sorted students: ')
print(my_dict[student1])
print(my_dict[student2])
print(my_dict[student3])
print(my_dict[student4])
print(my_dict[student5])
print(my_dict[student6])
print('The correct order: ')
print(sorted_key)
Reply
#2
If you look at your post, you will see why you need to put code inside the python delimiters. Easiest way is to click on the blue and yellow python sign in the posting editor then paste your code between those tags.
Reply
#3
Functions are easy. What you have done is much harder. This is a function:
def func_name([args]): # Things in [] are optional
    body
    [return value]
Lets try sorting the dictionary. You already do this, but we can do it in a function that allows specifying a different key for the sort. To make this really useful the function is written so that you pass in the dictionary and the key, and the function returns a new, sorted dictionary. Don't use global variables when you don't have to.
def sort_by_key(d, sort_key):
    '''Sort dictionary d by the sort_key in the dictionaries value
    Return sorted dictionary.
    '''
    sorted_keys = sorted(d.keys(), key=lambda key: d[key][sort_key])
    return {key:d[key] for key in sorted_keys}

sorted_by_growth = sort_by_key(m_dict, 'growth')
The function sort_by_key has two arguments, 'd' and 'sort_key'. I took your code to create a list of dictionary keys sorted by one of the keys in the dictionary value. The sorted keys are used in a dictionary comprehension to build a new dictionary in the order the keys appear. Finally the new dictionary is returned.
Reply
#4
You can improve your data structure.

In your example you give all persons a number (as a str).
Instead, you could collect the persons in a list and get rid of this number.

Some examples with the changed data structure:
from operator import itemgetter
from itertools import groupby
# read in the docs what itemgetter and groupby does.


def get_by(data, key, value):
    """
    Filter by key=value and return a new list.
    """
    sentinel = object()
    # unique object as sentinel for missing value
    results = []
    for element in data:
        if element.get(key, sentinel) == value:
            results.append(element)
    return results


def sort_by(data, *keys):
    """
    Sort data by keys and return a new list.
    """
    getter = itemgetter(*keys)
    return sorted(data, key=getter)


def group_by(data, key):
    """
    Sort and group data by a key.
    A dict with results is returned
    """
    sorter = sort_by(data, key)
    getter = itemgetter(key)
    return {
        group: list(values) for group, values
        in groupby(sorter, key=getter)
    }

# I converted your data:
# persons = list(my_dict.values())
# this will put only the values in the list
# and the key, which is the student number in your case, is gone.

persons = [{'gender': 'm', 'growth': 183, 'name': 'Elon', 'surname': 'Musk'},
 {'gender': 'f', 'growth': 175, 'name': 'Enola', 'surname': 'Holmes'},
 {'gender': 'f', 'growth': 178, 'name': 'Lilly', 'surname': 'Brown'},
 {'gender': 'm', 'growth': 189, 'name': 'Ragnar', 'surname': 'Lothbrok'},
 {'gender': 'f', 'growth': 173, 'name': 'Adreana', 'surname': 'Smith'},
 {'gender': 'm', 'growth': 184, 'name': 'Larry', 'surname': 'Moon'}]
Some examples:
Output:
In [2]: sort_by(persons, "growth") Out[2]: [{'gender': 'f', 'growth': 173, 'name': 'Adreana', 'surname': 'Smith'}, {'gender': 'f', 'growth': 175, 'name': 'Enola', 'surname': 'Holmes'}, {'gender': 'f', 'growth': 178, 'name': 'Lilly', 'surname': 'Brown'}, {'gender': 'm', 'growth': 183, 'name': 'Elon', 'surname': 'Musk'}, {'gender': 'm', 'growth': 184, 'name': 'Larry', 'surname': 'Moon'}, {'gender': 'm', 'growth': 189, 'name': 'Ragnar', 'surname': 'Lothbrok'}] In [3]: sort_by(persons, "growth", "gender") Out[3]: [{'gender': 'f', 'growth': 173, 'name': 'Adreana', 'surname': 'Smith'}, {'gender': 'f', 'growth': 175, 'name': 'Enola', 'surname': 'Holmes'}, {'gender': 'f', 'growth': 178, 'name': 'Lilly', 'surname': 'Brown'}, {'gender': 'm', 'growth': 183, 'name': 'Elon', 'surname': 'Musk'}, {'gender': 'm', 'growth': 184, 'name': 'Larry', 'surname': 'Moon'}, {'gender': 'm', 'growth': 189, 'name': 'Ragnar', 'surname': 'Lothbrok'}] In [5]: list(enumerate(persons)) Out[5]: [(0, {'gender': 'm', 'growth': 183, 'name': 'Elon', 'surname': 'Musk'}), (1, {'gender': 'f', 'growth': 175, 'name': 'Enola', 'surname': 'Holmes'}), (2, {'gender': 'f', 'growth': 178, 'name': 'Lilly', 'surname': 'Brown'}), (3, {'gender': 'm', 'growth': 189, 'name': 'Ragnar', 'surname': 'Lothbrok'}), (4, {'gender': 'f', 'growth': 173, 'name': 'Adreana', 'surname': 'Smith'}), (5, {'gender': 'm', 'growth': 184, 'name': 'Larry', 'surname': 'Moon'})] In [6]: group_by(persons, "gender") Out[6]: {'f': [{'gender': 'f', 'growth': 175, 'name': 'Enola', 'surname': 'Holmes'}, {'gender': 'f', 'growth': 178, 'name': 'Lilly', 'surname': 'Brown'}, {'gender': 'f', 'growth': 173, 'name': 'Adreana', 'surname': 'Smith'}], 'm': [{'gender': 'm', 'growth': 183, 'name': 'Elon', 'surname': 'Musk'}, {'gender': 'm', 'growth': 189, 'name': 'Ragnar', 'surname': 'Lothbrok'}, {'gender': 'm', 'growth': 184, 'name': 'Larry', 'surname': 'Moon'}]}
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  dictionary output to text file (beginner) Delg_Dankil 2 1,186 Jul-12-2023, 11:45 AM
Last Post: deanhystad
  How to convert .trc/.txt file into excel using python ebola 3 2,017 Jan-15-2023, 10:37 PM
Last Post: Yoriz
  Using dictionary to find the most sent emails from a file siliusu 6 7,587 Apr-22-2021, 06:07 PM
Last Post: siliusu
  Updating dictionary in another py file tommy_voet 1 4,891 Mar-28-2021, 07:25 PM
Last Post: buran
  Making a dictionary from a file instyabam 0 1,508 Oct-27-2020, 11:59 AM
Last Post: instyabam
  how can i create a dictionary of dictionaries from a file Astone 2 2,261 Oct-26-2020, 02:40 PM
Last Post: DeaD_EyE
  Functions returns content of dictionary as sorted list kyletremblay15 1 2,046 Nov-21-2019, 10:06 PM
Last Post: ichabod801
  how to put text file in a dictionary infected400 2 3,004 Jan-06-2019, 04:43 PM
Last Post: micseydel
  Python code to convert executable file to doc or pdf Micmilli2 3 2,969 Oct-11-2018, 10:15 AM
Last Post: Larz60+
  Dictionary to .txt or .csv file stanthaman42 9 4,674 Aug-08-2018, 03:37 PM
Last Post: Vysero

Forum Jump:

User Panel Messages

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