Skip to main content

manage_friends_json.py

Download source

manage_friends_json.py
# 1. Create a dictionary friends and add the following persons as
#    friend1, friend2, ...:
#    Peter likes biking and techno. He does not tolerate peppers and cucumbers.
#    Maria likes dancing and skiing. She does not tolerate nuts.
friends = {
    "friend1": {
        "name": "Peter",
        "likes": ["biking", "techno"],
        "food_intolerances": ["pepper", "cucumber"],
    },
    "friend2": {
        "name": "Maria",
        "likes": ["dancing", "skiing"],
        "food_intolerances": ["nuts"],
    },
}

# 2. Save the dictionary to a file named "friends.db".
import json

file = open("friends.db", "w")
json.dump(friends, file)

# 3. Remove all variables from kernel namespace in Spyder.

# 4. Read the contents of the file "friends.db" into a dictionary friends.
import json

file = open("friends.db", "r")
friends = json.load(file)

# 5. Show the dictionary, only friend1, the name of friend1, and the likes
#    of friend2.
friends
friends["friend1"]
friends["friend1"]["name"]
friends["friend2"]["likes"]

# 6. Add Jane, age 22, who likes hiking and dancing, to the dictionary.
#    She does not tolerate gluten and milk.
friends["friend3"] = {
    "name": "Jane",
    "age": 22,
    "likes": ["hiking", "dancing"],
    "food_intolerances": ["gluten", "milk"],
}

# 7. For Peter, add reading to his likes.
friends["friend1"]["likes"].append("reading")

# 8. For Jane, delete her age.
del friends["friend3"]["age"]

# 9. For Maria, delete Skiing from her likes.
friends["friend2"]["likes"].remove("skiing")

# 10. Delete Peter, as he is no longer your friend.
del friends["friend1"]

# 11. Save the dictionary to "friends.db".
file = open("friends.db", "w")
json.dump(friends, file)