0

I'm getting a weird key error with Python dicts. My key is "B19013_001E" and I've named my dict "sf_tracts" with a nested dict "properties". Here is my code:

x = "B19013_001E"
for tract in sf_tracts:
    print tract["properties"][x]

With this, I get a KeyError: "B19013_001E"

However if I change the code to this, the values get printed:

x = "B19013_001E"
for tract in sf_tracts:
    for key in tract["properties"]:
        if key == "B19013_001E":
            print tract["properties"][x]

What's the difference?

-edit- I believe the issue is the underscore as other keys can be printed. How do I access this key?

Thanks

4
  • 1
    what exactly is in sf_tracts Commented Aug 24, 2016 at 16:40
  • 2
    There is nothing special about underscores in strings. What does print list(tract['properties']) produce? Can you share the exact quoted representation of that one key? Commented Aug 24, 2016 at 16:41
  • 7
    You have more than one dictionary in sf_tracts. Not all those dictionaries have that key. Your for key in dictionary loop can be replaced with if x in tract["properties"]: print tract["properties"][x], by the way, no need to loop. Commented Aug 24, 2016 at 16:42
  • @MartijnPieters oh, I believe that is the issue, let me check Commented Aug 24, 2016 at 16:43

2 Answers 2

3

You are assuming that the key exists in all dictionaries that the tract in sf_tracts loop produces. That assumption is incorrect.

Your second piece of code happens to work because you are essentially testing for the key to exist, albeit expensively. You could instead do this:

for tract in sf_tracts:
    if x in tract["properties"]:
        print tract["properties"][x]

or you could use:

for tract in sf_tracts:
    print tract["properties"].get(x, 'Key is not present')

There is otherwise nothing special about a string key with an underscore in the value. An underscore makes no difference to how such keys are treated.

Sign up to request clarification or add additional context in comments.

Comments

1

Some of your tracts must be missing that particular key. In the first case, you're asking every tract to print the key, while in the second you're limiting the print operation to only those that have the key.

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.