Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python basic list/dict operations
# This blurb will find entries in a list of dictionaries that match a pattern
# This requires Python 3.6 or greater since I'm using f-strings to print the variable (WAY easier than .format())
# Import json library to work with the data_blob string (which is a JSON object)
import json
data_blob = '''{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
],
"baking_method":
[
{ "id": "1001", "type": "Oven" }
],
"price_info":
[
{ "id": "5001", "price": "2.25", "unit": "ea" },
{ "id": "5002", "price": "2.25", "unit": "ea" },
{ "id": "5005", "price": "2.25", "unit": "ea" },
{ "id": "5007", "price": "1.99", "unit": "ea" },
{ "id": "5006", "price": "2.19", "unit": "ea" },
{ "id": "5003", "price": "1.59", "unit": "ea" },
{ "id": "5004", "price": "2.45", "unit": "ea" }
]
}'''
# Convert the JSON blob to a Python dictionary
data_json = json.loads(data_blob)
# Print the top level ID
print(f'Document ID: { data_json["id"] }')
# Print the raw list "topping"
print(data_json["topping"])
# Tell me how many items are in the list using the len()
print(f'There are { len(data_json["topping"]) } donut toppings.')
# A simple if then check to see how many items are in a list, and vary the output
if len(data_json["baking_method"]) == 1:
print('There is 1 baking method.')
else:
print(f'There are { len(data_json["baking_method"]) } baking methods.')
# Print the first entry in the "topping" list
# Lists are ordered, dictionaries are not, numbering starts at zero
print(data_json["topping"][0])
# Print the third entry in the list
print(data_json["topping"][2])
# Print just the ID of the first topping in the first entry
print(f'ID: { data_json["topping"][0]["id"] }')
# Perform a basic iteration through the toppings, printing out each ID and type in a formatted manner
# You have to set the iteration on a list, since
for topping in data_json["topping"]:
print(f'ID: { topping["id"] } Type: { topping["type"] }')
# Let's iterate through both the keys and the values, looking for only topping IDs that are priced at 2.25 each and turn it into a list
# Create an empty list
item_list = []
# Start the iteration cycle
for item in data_json["price_info"]:
# "item" is each individual dictionary, so do an if check to see if the "price" key is 2.25
if item["price"] == '2.25':
# If so, append it to the list called item_list
item_list.append(item["id"])
# print the item_list to console
print('Topping IDs that cost 2.25: ', item_list)
# Time to look the item ID up to find out the topping name
# For this, we use a nested for statement.
# We iterate through the first list (of IDs)
for topping_id in item_list:
# Then we iterate over the second list, comparing it to the second list (ID to names)
for topping_name in data_json["topping"]:
if topping_id == topping_name["id"]:
print(topping_name["type"])
# Show me all the keys in data_json dictionary
# print(data_json.keys())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.