Home > json, Learning, Lesson, Projects/Experiments, Python > Python: My Fake Data Generator P-6

Python: My Fake Data Generator P-6



Learning : Python: Functions, Procedures and documentation
Subject: About fake data P-6: (Fake Food List)

In the last post the function we create def get_animal_name() get it’s data or let’s say select a random animal names from a dictionary data-set after loading the data from json file through URL, and I upload the Python functions on my Download Page so you can use it. Also I am working on standardizing my data-sets json file and adding information key for each file.

In this post we will write the code to print-out a random selected Food. The function will ask the user if he/she wants random list of Fruit, Vegetables or Meals. The Food data-set is growing up and i am adding more items to it, from the last update, the Meals contains: breakfast from UK, France and USA and Planning to add Dinners and Lunches recipes from more countries.

Let’s Start .. First we will load the json file, here is the code..

 #Calling and loading the json data-set file 

 #Importing libraries
import json , requests, random 


fname = "https://raw.githubusercontent.com/Ali-QT/Ideas-and-Plan/master/foods.json"

def call_json_url(fname): 
 #    """ 
    Function to load the json file from URL. 
    Argument : str  : fname 
    return   : dict : data 
    """ 
    req = requests.get(fname) 
    cont = req.content 
    data = json.loads(cont) 
    return data  # retuning the data-set

data = call_json_url(fname)


Now, we have several other functions in this application, first we will list them and then we will see the code in each one.
So here is the list:

  • get_type_index (adata,akey,subkey,aval)
    Function to return a list with index numbre of akey (atype).
    Argument: dic : adata, str : atype
    Return : list : ind_list
  • get_f_or_v(adata,atype)
    Function to print-out the Fruits or Vegetables as the user ask for.
    Argument: dict : adata, str : atype
  • get_meals (adata)
    Function to print-out the Meal as user will select. The user can select the Type of Meal: Breakfast, Dinner and Lunch. Also the user can select the countries of the Meals.

    Argument: dict: adata

  • def mmenu()
    This is the main menu to help the user to select whatever he/she want to be ptint-out.

Main Menu: Very short easy menu of four selection number as following:

 #The menu function


def mmenu() :
    """
        This is the main menu to help the user to select whatever want to be ptint-out.
    
    
    """
    print('\n\n  In the Food data-set we have several keys, here they are:')
    print('  Fruits, Vegetables and Meals. This application will select a random items\n  of your selection to print it on the screen.')
    print('  also you can select the number of items you want.\n ')
    print('  First, What type of Food do you want? ')
    print('   1. Fruits.')
    print('   2. Vegetables.')
    print('   3. Meals')
    print('   4. To exsit enter Q or q')

    ft = input('  Select one item:')
    if ft =='1' :
        get_f_or_v(data,'1')

    elif ft =='2' :
        get_f_or_v(data,'2')
    elif ft == '3' :
        get_meals (data)
    elif ft in ['q','Q']:
        print('Close')
        return 'q'
    else :
        print('\n   We only have three items') 
      


If the user select (1 or 2 ), then we will call the get_f_or_v(data,the user selection), the first argument is the data-set, the second one is the user selection between Fruit, Vegetables or Meal. Here is the function ..

 #Calling and Menu 

def get_f_or_v(adata,atype):
"""
       Function to print-out the Fruits or Vegetables as the user ask for.
       Argument:   dict   :  adata
                     str  :  atype      
    """
    if atype == '1': ft = 'fruits'  
    else: ft = 'vegetables'
    fts = len(adata[ft])
    while True :
        s = input('\n  You select {}, we have list of {} {}, So how many\n  {} you want to print: '.format(ft,fts,ft,ft))
     
        if int(s) < fts :
            break
        else : 
            print('  Enter a number in range 0 to {}.'.format(fts))
    print('Random {} names are:'.format(ft))
    for x in range (int(s)) :
        ind = random.randint(1,fts) 
        print('   ',adata[ft][ind]['name'])
    
    input('\n    ... Press any key ... ')


Last function we will see here is to get random Meals, I am loading the data from a json file that i create, for-now we have a breakfast only from UK, USA and France. If the user select the Meals from first menu, then another short menu will pop-up here it is ..

 #Calling get Meals 

def get_meals (adata) :	
	    """
	        Function to print-out the Meal as user will select. The user can select the Type of Meal: Breakfast, Dinner and Lunch.  
	        Also the user can select the countries of the Meals. 
	        
	        Argument:    dict: adata
	    """
	
    ft = 'meals'
    fts = len(adata[ft])
	 
    while True :
        s = input('\n  You select {}, we have list of {} {}, So how many\n  {} you want to print: '.format(ft,fts,ft,ft))
     
        if int(s) < fts :
            break
        else : 
            print('  Enter a number in range 0 to {}.'.format(fts))
        
    print('\n  For Meals we have Breakfast from three counties:')
    print(' 1. UK.')
    print(' 2. USA.')
    print(' 3. France.')
    co = input(' Select a country:')
    if co == '1' : co ='UK'
    elif co == '2' : co ='USA';
    else : co ='FR' 
          
    ind_list = get_type_index(adata,ft,'country',co) 
    
    for x in range (0,int(s)):
        ind = random.choice(ind_list)
        print(adata[ft][ind]['name'],'is a ', adata[ft][ind]['time'],'from ',adata[ft][ind]['country'])
  
    input('\n    ... Press any key ... ')


Notes that in def get_meals() I use a hard-coded keys for the menu. I am working on a function to read any json file and get a list of all keys and sub-keys in any level, then giving the user the ability to walk-through all the data. This will be in coming post.



:: Fake Function List ::

Function Name Description
Color To return a random color code in RGB or Hex.
Date To return a random date.
Mobile To return a mobile number.
Country To return a random country name.
City To return a random City name.
ID To return X random dig as ID.
Time To return random time.
Car’s Brand
file_name file name: list for fake file names.
Creatures Random animal names of a certain type: Mammals, Birds, Insect, Reptiles
Foods To return a random list of foods

Done



Follow me on Twitter..




By: Ali Radwani




  1. No comments yet.
  1. January 19, 2020 at 9:44 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: