Python Key Error With _ - python

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

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.

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.

Related

How can I search for a specific key in a dictionary in Python?

So I got this dictionary from a csv file and I would like to look for a specific key inside this dictionary (actually the og idea was to search for said key in the csv file and then make a dictionary from that key down) but I don't really know how to do it.
So far I got:
df = pd.read_csv('data.csv')
dict = df.to_dict(orient='dict')
for index, line in enumerate(dict):
if "Wavelength [nm]" in line:
print(index)
The idea is to know the index of "Wavelength".
If you want the value of a key without knowing whether it's in the dict, often the most natural way is
value = dict.get( key, defaultvalue)
defaultvalue is what you would set value to in your code once you had established that the key is not present. Often, None, or an empty list or tuple.
If you just waht to check whether the key is present without accessing the value, use
if key in dict:
# do stuff
you can use:
if key in dict:
print(key,dict[key])

How can I print key and value of a dictionary together in a single print() function as in the given code?Error : NameError: name 'Key' is not defined

dict = {"Pond":"A Lake",
"Lake":"A Pond",
"Book":"Bunch of Pages",
"Chaddi":"The Undies"
}
for key in dict:
print(f"{Key}:{dict[key]}")
You incorrectly capitalized the letter k. You wrote Key. Use key.
If d is your dictionary (you should not use dict as the name of your dictionary):
for key in d:
print(f"{key}:{d[key]}")
Someone has already solved your mistake.
Here I did other alternative solutions, and more understandable.
for key, value in dict.items():
print(key,":",value)
A few things. First you simply misspelled the word key, as answered by #oda. Fix that capital k in the print function and your code will work.
Second, don't call a dictionary dict, since dict is already a function in python:
d = dict()
creates a new empty dictionary.
If you create a variable named dict you'll overshadow the dict function and you'll probably get some error sooner or later.

Dictionary key and string comparison in python

I compared the dictionary key with a predefined string, eventhough it looks similar, but the comparison always fails.
for example: key='eng-101' and 'eng-101' string are not same.
please help
for key, value in course_dict.items() :
print('search ky is --'+key)
print('the elective courses are---',courses)
#finding the key in string
if(courses.find(key)==-1):
print('key not found--'+key)
else:
print('---------------------the key found is---'+key)
key=str(key +'-101,')
key=key.replace(' ','')
first_year_el_course+=key
print(elective_counter)
print(first_year_el_course)
print('newly formatter key--: '+key)
print(key=='eng-101')
Change:
key=str(key +'-101,') # Remove the comma at the end, otherwise key will be 'eng-101,' and not 'eng-101'.
To:
key = str(key) + '-101' # Convert key to string. '-101' is already a string.
#DipenDadhaniya is correct but it is always better to use string formatting. This should make your code more concise and easy to read.
Be careful about changing the iteration variable key during an iteration as this can sometimes lead to unintended consequences which can be difficult to debug. Give it a new name such as new_key.
new_key = '{}-101'.format(key.replace(' ', ''))

Why does the default dictionary in my code keep expanding?

I have a default dictionary and I run it through a couple of loops to look for certain strings in the dictionary. The loops don't really append anything to the dictionary yet as it turns out, during the loop, new items keep getting appended to the dictionary and the final dictionary ends up bigger than the original one before the loop.
I've been trying to pinpoint the error forever but now it's late and I have no idea what's causing this!
from collections import defaultdict
dummydict = defaultdict(list)
dummydict['Alex'].append('Naomi and I love hotcakes')
dummydict['Benjamin'].append('Hayley and I hate hotcakes')
part = ['Alex', 'Benjamin', 'Hayley', 'Naomi']
emp = []
for var in dummydict:
if 'I' in dummydict[var]:
emp.append(var)
for car in part:
for key in range(len(dummydict)):
print('new len', len(dummydict))
print(key, dummydict)
if car in dummydict[key]:
emp.append(car)
print(emp)
print('why are there new values in the dictionary?!', len(dummydict), dummydict)
I expect the dictionary to remain unchanged.
if car in dummydict[key]:
key being an integer, and your dict being initially filled with only string as keys, this will create a new value in dummydict for each key.
Accessing missing keys as in dummydict[key] will add those keys to the defaultdict. Note that key is an int, not the value at that position, as for key in range(len(dummydict)) iterates indexes, not the dict or its keys.
See the docs:
When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list.
For example, this code will show a dummydict with a value in it, because simply accessing dummydict[key] will add the key to the dict if that key is not already there.
from collections import defaultdict
dummydict = defaultdict(list)
dummydict[1]
print (dummydict)
outputs:
defaultdict(<class 'list'>, {1: []})
Your issue is that in your loop, you do things like dummydict[key] and dummydict[var], which adds those keys.

Iterating over A dict to access a specific key value

I have a list of dicts ('sortings') that I am trying to iterate through to access a values in one specific key of each dict. My code keeps saying that there is a key error for the desired value in the dict. If I print inside the for loop, it prints with the values entered but once I exit the for loop it says there is a key error.
for i in range(sort_len):
sentence = sortings[i]['content']
containing_messages.append(sentence)
print(containing_messages)
This is an answer for my understanding of the question. I would require the given input and expected output to provide a better answer.
list_of_dicts = [{'keya':'value1_1','keyb':'value2_1','keyc':'value3_1'},
{'keya':'value1_2','keyb':'value2_2','keyc':'value3_2'},
{'keya':'value1_3','keyb':'value2_3','keyc':'value3_3'}]
list_of_key_values = [my_dict['keyb'] for my_dict in list_of_dicts]
print list_of_key_values

Categories