0

I'm quite confused on why I keep getting KeyError: None, I would like to get the user to enter a Name(e.g. Lisbon) and return other Users in the JSON file(e.g. Jade, John) that falls under the same Country as what the User Inputs(e.g. Lisbon), I have a JSON file that looks like this:

{  
   "user1":{  
      "Country":[  
         "China",
         "USA",
         "Nepal"
      ],
      "Name":[  
         "Lisbon"
      ]
   },
   "user2":{  
      "Country":[  
         "Sweden",
         "China",
         "USA"
      ],
      "Name":[  
         "Jade"
      ]
   },
   "user3":{  
      "Country":[  
         "India",
         "China",
         "USA"
      ],
      "Name":[  
         "John"
      ]
   }
}

And here's my code

userName = raw_input("Enter user's name: ")
with open('listOfUsers.json') as f:
    data = json.load(f)

def getId(name):
  for userId, v in data.items():
    if v['Name'] == name:
        return userId;

id = getId(userName)
for k, v in data.items():
  if any(x in data[id]['Country'] for x in v['Country']):
      print(k)

How do I go around this problem?

1 Answer 1

3

Your getId function always returns None. This is because if v['Name'] == name: will never succeed. v['Name'] is a list, and name is a string, and a list and a string never compare equal.

If possible, modify the format of your json file so that the Name value is a string, not a list of strings.

"user1":{
    "Country":[
        "China", "USA", "Nepal"
    ],
     "Name": "Lisbon"
},
//etc

If this is not possible, modify getId so it inspects the first element of the list.

def getId(name):
  for userId, v in data.items():
    if v['Name'][0] == name:
        return userId
Sign up to request clarification or add additional context in comments.

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.