Take this example:
"something": {
"random": 0,
"bag": {
"papers": 0,
"pencils": 0
},
"PAINT": {
"COLORS": [
"A WHITE",
"B MAPLE",
"B LOTUS",
"A OLIVE"
],
"CANS": [
"SOMETHING"
]
}
Ignore everything and focus on the COLORS list in the PAINT dictionary… I want to print all colors that have the color A before them, as a code. In other words I want to print "A WHITE" and "A OLIVE". Here’s what happens when I do this:
with open("somethings.json", "r") as f:
data = json.load(f)
print(data["something"]["PAINT"]["COLORS"])
This is the output:
["A WHITE", "B MAPLE", "B LOTUS", "A OLIVE"]
but like I said, I do not want that… I want only A colors to be printed…
I also do not want THIS:
["A WHITE", "A OLIVE"]
the output that I really want (which is quite specific) is this:
OLIVE
WHITE
With line breaks (optional: AND in alphabetical order) that is the output that I want. So how can I print this output? is it possible without using any ‘for’ loops? This is a very specific question, would appreciate some help. Thanks –
>Solution :
Try this code:
with open("somethings.json", "r") as f:
data = json.load(f)
a_colors = [color for color in data["something"]["PAINT"]["COLORS"] if color.startswith("A ")]
colors = [a_color.replace("A ", "") for a_color in a_colors]
print(colors)
How it works
- Opens and loads the JSON data.
- Uses a list comprehension to filter only entries that start with
"A ".
The.startswith()method of a string returns a boolean value,Trueif the first few characters of the string are, in fact, the characters passed as an argument, andFalseotherwise. - Uses another list comprehension to get the string without the
"A "for each string in the list created in step 2.
Replaces the"A "with an empty string, which is a hacky way of deleting part of a string using the.replace()method.
It can be done without list comprehensions using a for loop as well
See code below:
with open("somethings.json", "r") as f:
data = json.load(f)
a_colors = []
for color in data["something"]["PAINT"]["COLORS"]:
if color.startswith("A "):
color_without_a = color.replace("A ", "")
a_colors.append(color_without_a)
print(a_colors)
This solution uses a for loop rather than a list comprehension but is otherwise the same. (If you are confused, see below for a solution which is an exact replica of the list comprehension one but implemented with for loops).
If you are interested, here is a lengthier solution more similar to the list comprehension one, using for loops:
with open("somethings.json", "r") as f:
data = json.load(f)
a_colors = []
for color in data["something"]["PAINT"]["COLORS"]:
if color.startswith("A "):
a_colors.append(color)
colors = []
for a_color in a_colors:
colors.append(a_color.replace("A ", ""))
print(a_colors)
Recommended reading
- Python Data Structures documentation
- Examples of list comprehensions for practice
- Beginner’s list comprehension tutorial
- Filtering lists in Python
Other helpful resources
I strongly recommend watching this video as well:
Thank you for reading! Please upvote if you found it helpful!