1

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?

1
  • 2
    I'm guessing your structure is supposed to be a dictionary inside of a dictionary inside of a dictionary (dictinception). Such as 'key#' is a dictionary to the key 'keys' and that is part of a dictionary inside of key 'thing' which includes also keys 'name' and 'thing'. If this is the case you need to look at the python syntax for this which is { } is the start and end of a dictionary. You may reference the keys using [ ] but you don't declare them that way. Commented Apr 18, 2017 at 23:26

2 Answers 2

2

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
    } } }
] 
Sign up to request clarification or add additional context in comments.

Comments

0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.