BrinkDaDrink
BrinkDaDrink

Reputation: 1798

Check whether a given value is in a nested dictionary

I have this structure, converted using json.load(json)

jsonData = [ { 
thing: [
    name: 'a name',
    keys: [
        key1: 23123,
        key2: 83422
    ]
thing: [
    name: 'another name',
    keys: [
        key1: 67564,
        key2: 93453
    ]
etc....
} ]

I have key1check = 67564, I want to check if a thing's key1 matches this value

if key1check in val['thing']['keys']['key1'] for val in jsonData:
    print ('key found, has name of: {}'.format(jsonData['thing']['name'])

Should this work? Is there a better was to do this?

Upvotes: 1

Views: 799

Answers (2)

shearos
shearos

Reputation: 129

You can loop through @Prune 's dictionary using something like this as long as the structure is consistent.

for item in jsonData:
    if item['thing']['keys']['key1'] == key1check:
        print("true")
    else:
        print("false")

Upvotes: 0

Prune
Prune

Reputation: 77837

Not quite:

  1. in is for inclusion in a sequence, such as a string or a list. You're comparing integer values, so a simple == is what you need.
  2. Your given structure isn't legal Python: you have brackets in several places where you're intending a dictionary; you need braces instead.

Otherwise, you're doing fine ... but you should not ask us if it will work: ask the Python interpreter by running the code.

Try this for your structure:

jsonData = [ 
{ "thing": {
    "name": 'a name',
    "keys": {
        "key1": 23123,
        "key2": 83422
    } } },
{ "thing": {
    "name": 'another name',
    "keys": {
        "key1": 67564,
        "key2": 93453
    } } }
] 

Upvotes: 2

Related Questions