Skip to content

Instantly share code, notes, and snippets.

@liamkeegan
Last active October 14, 2021 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liamkeegan/ec6980284dfcfe69bf7120eeb3f7076d to your computer and use it in GitHub Desktop.
Save liamkeegan/ec6980284dfcfe69bf7120eeb3f7076d to your computer and use it in GitHub Desktop.
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" }
]
},
"toppings":
[
{ "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 "toppings"
print(data_json["toppings"])
# Tell me how many items are in the list using the len()
print(f'There are { len(data_json["toppings"]) } 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["toppings"][0])
# Print the third entry in the list
print(data_json["toppings"][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["toppings"]:
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())
# This example iterates through the keys/values in the lookup dict to find the key associated with a value.
mytable = {
"lookup": {
"infra": ["UCSB-5108", "UCS-IOM-", "UCSB-PSU-", "CAB-", "UCS-SID", "N20-", "N01-"],
"snt": ["CON-"],
"blade": ["UCSB-B200-M5", "UCS-CPU", "UCSB-MRAID", "UCS-MR", "UCSB-MLOM", "UCS-HD"],
"sfp": ["QSFP-", "SFP-"]
},
"price":{
"infra": 55,
"snt": 22,
"blade": 22,
"sfp": 55,
"none": 0
}
}
print([group for (group,value) in mytable['lookup'].items() if 'UCS-CPU' in value])
> ['blade']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment