Friday, January 15, 2021

Python - Dictionaries and Nesting (Day 9)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Dictionaries



Like real life dictionaries, it contains keys (Vocabulary) and its value (Definition) for users to easily access. Reference


Ex:
# Define a dictionary
# The values of a dictionary can be any type
# But the keys must be one of an immutable data type such as string,
# number, or tuples
user_info = {
    "name": "Frank",
    "gender": "Male",
}



Some Basic Usage



Ex:
# Define a dictionary
user_info = {
    "name": "Frank",
    "gender": "Male",
}

# Print dictionary elements
print(user_info)

# Get dictionary element by its key
print(user_info["name"])

# Adding a new item to dictionary
# or edit an existing item in a dictionary
user_info["address"] = "xxx"
print(user_info)
user_info["address"] = "xxxx"
print(user_info)

# Loop through a dictionary
for key in user_info:
    print(user_info[key])

# Checking length
print(len(user_info))

# Empty dictionary/Wipe an existing dictionary
user_info = {}
print(user_info)

Result:
{'name': 'Frank', 'gender': 'Male'} Frank {'name': 'Frank', 'gender': 'Male', 'address': 'xxx'} {'name': 'Frank', 'gender': 'Male', 'address': 'xxxx'} Frank Male xxxx 3 {}



More Complex Case



Ex:
# Nesting a List in a Dictionary
travel_log = {
    "Asia": [
        "Korea",
        "Japan"
    ],
    "North America": [
        "Canada",
        "US"
    ],
}
print(travel_log)

# Nesting a Dictionary in a Dictionary
travel_log = {
    "Asia": {
        "visited": ["Korea", "Japan"],
        "total_visits": 5
    },
    "North America": {
        "visited": ["Canada", "US"],
        "total_visits": 3,
    },
}
print(travel_log)

# Nesting Disctionary inside a List
travel_log = [
    {
        "Area": "Asia",
        "visited": ["Taiwan", "Japan"],
        "total_visits": 5
    },
    {
        "Area": "North America",
        "visited": ["Canada", "US"],
        "total_visits": 3,
    }
]
print(travel_log)

Result:
{
'Asia': ['Korea', 'Japan'],
'North America': ['Canada', 'US']
}
{
'Asia': {
'visited': ['Korea', 'Japan'],
'total_visits': 5
},
'North America': {
'visited': ['Canada', 'US'],
'total_visits': 3
}
}
[
{
'Area': 'Asia',
'visited': ['Taiwan', 'Japan'],
'total_visits': 5
},
{
'Area': 'North America',
'visited': ['Canada', 'US'],
'total_visits': 3
}
]



Challenge - The secret auction game



What is it? Reference

Ex:
# Define a flag to determine the while loop should be stopped or not
game_is_ended = False

# Define a dictionary to store name as a key and the bid as a value
bids = {}

# Define a custom Func to determine the winner (highest bid)
def check_highest_bid():
    max_bid = 0
    winner = ""

    for key in bids:
        if bids[key] > max_bid:
            max_bid = bids[key]
            winner = key

    print(f"The winner is {winner} with a bid of ${max_bid}")
# Loop for the user input
while not game_is_ended:
    # Ask user for the name and their bid
    name = input("What is your name?:")
    bid = int(input("What is your bid?: $"))

    # Add it to the dictionary
    bids[name] = bid

    # Ask for keep continued or not
    should_continue = input("Are there any other bidders? Type 'yes or
'no'.")
    if should_continue == 'no':
        game_is_ended = True

  # Check the result
check_highest_bid()

Result:
What is your name?:Frank What is your bid?: $10
Are there any other bidders? Type 'yes or 'no'.yes
What is your name?:Jake What is your bid?: $20
Are there any other bidders? Type 'yes or 'no'.no The winner is Jake with a bid of $20


No comments:

Post a Comment