Home > database >  Print a specific key from json file
Print a specific key from json file

Time:12-01

I'm trying to print a specific key from a dictionary(key:value) like this in a JSON file(below). I tried this code but prints everything:

reda.json:

[{"alice": 24, "bob": 27}, {"carl": 33}, {"carl": 55}, {"user": "user2"}, {"user": "user2"}, {"user": "123"},]

Python:

import json
filename = 'reda.json'

json_data = json.load(open('reda.json'))
if type(json_data) is dict:
    json_data = [json_data]
for i in json_data:
    print(i)

CodePudding user response:

You could turn the list of dicts into a single dict. Downside is dups would be squished, so e.g. "carl" would map to just a single number.

As it stands, you probably want to see all of carl's values, using something like this:

json_data = json.load(open('reda.json'))
for d in json_data:
    print(d)

k = "carl"
print(f"\nHere is {k}:")
for d in json_data:
    if k in d:
        print(k, d[k])

To see if e.g. "carl" is in the data, use this:

def contains_favorite_key(d: dict, k="carl"):
    return k in d

if any(map(contains_favorite_key, json_data)):
    print("found at least one occurrence!")


To say "bye, bye, Carl!" use del:

k = "carl"
assert k in d
print(d[k])

del d[k]

print(d[k])  # Notice that this now reports KeyError.
  • Related