Dictionary key and string comparison in python - 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(' ', ''))

Related

Is there a way to search by key in a dictioanry in a list, even when you're not sure where the dictionary is?

I have a weird json file to work with. I'm trying to find the key dt in a dictionary in a list. The problem is that sometimes it can be something like a dictionary in a list in a list or a dictionary in a dictionary or a list.
The "dt" key exists, but the position isn't guaranteed. Is there a way for me to get this key? At first, I tried using many if and for statements, but I realized it would be too much.
I then tried converting the json file to a string and using re.search to search for {'dt':, but I wasn't sure about that accuracy. Is there any way to search for the "dt" key without knowing the exact position of the dictionary? Thanks!
Is this what you were looking for ? Please note that I did not check all the use cases because I am not aware of all of them. Think it should cover all of them , but please validate. The code can be improved so much - this is just an initial version, hope you can improve on it :)
funcIter is a function that gets called over and over until dt is found. It checks if the input is of type dictionary and then iterates over the dictionary object to find the key. If it is of any other type if assumes it is of type list (you can add one more check to check specifically for type list) and then grabs the first item.
dicObject = {"value" :[{"dt":12345}]}
def funcIter(items):
if(isinstance(items, dict)):
for key, value in items.items():
if key.startswith('dt'):
print (key, value)
else:
funcIter(value)
else:
indexes = [n for n, x in enumerate(items) if x == 'dt']
if(len(indexes) < 1):
funcIter(items[0])
else:
print(items[0])
pass
funcIter(dicObject)
I finally did it! All that was needed was a recursive function. Below is the functioning recursive function.
def findDT(givenThing, key):
if isinstance(givenThing, dict):
for a in givenThing.keys():
if a == key:
print(givenThing[key])
return givenThing[key]
else:
findDT(givenThing[a], key)
elif isinstance(givenThing, list):
for a in givenThing:
if isinstance(a, list) or isinstance(a, dict):
givenThing = a
findDT(givenThing, key)

How to print the key of a dictionary but not it's value? [python]

I know this is probably extremely simple and I'm forgetting something, but I cannot remember how to print the key of a dictionary. The specific problem is I have a dictionary of parts of an animal that can attack, and the value is the verb used to attack, e.g: {'teeth': 'bites'}
It looks like this:
attack_part = random.choice(list(self.attacking_parts))
print('The', self.name, self.attacking_parts[attack_part], 'you with their', self.attacking_parts.keys() + '!')
But when I use this what happens is:
The bear scratches you with their scrathes!
attack_part variable in you code is the key of your dict. When you are doing the self.attacking_parts[attack_part], you are fetching the value corresponding to attack_part key in you self.attacking_parts dict. Whereas doing self.attacking_parts.keys() returns the list of all the keys present in the dict.
Hence, instead you should be using your print statement like:
print('The', self.name, self.attacking_parts[attack_part], 'you with their', attack_part + '!')

Python Key Error With _

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.

update string from a dictionary with the values from matching keys

def endcode(msg,secret_d):
for ch in msg:
for key,value in secret_d:
if ch == key:
msg[ch] = value
return msg
encode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})
This is my code. What I am trying to do here is for every characters in a string msg, the function should search in the dictionary and replace it with the mapping string if the character ch is a key in the dictionary secret_d.
If ch is not a key in secret_d than keep it unchanged.
For the example, the final result is should be 'C4N YOU R34D 7H15'
Your function name is endcode but you are calling encode.
But more important, I'll give you a hint to what's going on. This isn't going to totally work, but it's going to get you back on track.
def endcode(msg,secret_d):
newstr=""
for ch in msg:
for key,value in secret_d.iteritems():
if ch == key:
newstr=newstr+value
print(msg)
endcode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})
But if you want a complete answer, here is mine.
A few issues:
As rb612 pointed out, there's a typo in your function definition ("endcode")
you are doing nothing with the return value of your function after calling it
msg[ch] is trying to assign items in a string, but that's not possible, strings are immutable. You'll have to build a new string. You cannot "update" it.
in order to iterate over (key, value) pairs of a dictionary d, you must iterate over d.items(). Iterating over d will iterate over the keys only.
That being said, here's my suggestion how to write this:
>>> def encode(msg, replacers):
... return ''.join([replacers.get(c, c) for c in msg])
...
>>> result = encode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})
>>> result
'C4N YOU R34D 7H15'
Things to note:
dict.get can be called with a fallback value as the second argument. I'm telling it to just return the current character if it cannot be found within the dictionary.
I'm using a list comprehension as the argument for str.join instead of a generator expression for performance reasons, here's an excellent explanation.

Converting Unicode Values as String from a Python Dictionary

I've built a python dictionary as follows:
result = {}
for fc in arcpy.ListFeatureClasses():
for field in arcpy.ListFields(fc):
result.setdefault(field.name, []).append(fc)
which takes the name of the fields in each table (feature class) and sets tyhem as the key value in the dictionary and goes on to set the name of the table as the value. This works fine because my goal is to find out which tables have the same fields. I can go on to iter over the items and print out the key, value pairs:
for key, value in result.iteritems():
print key + ": " + str(value)
which returns:
COMMENTS: [u'TM_FC', u'GT_FC', u'HG_FC', u'PO_FC', u'FU_FC']
I want to print out the key values as a string value instead of the unicode stuff so that it looks like this:
COMMENTS: 'TM_FC', 'GT_FC', 'HG_FC', 'PO_FC', 'FU_FC'
I've been playing around with the 'str' function and various other ways to format and convert to string, but I'm always returning the same original value list. Can anyone suggest a way to accomplish what I'm looking for?
Thanks,
Mike
The issue in your code is that you are calling str(value), where value is an array. So what happens is that the array object's __str__ function is getting invoked and it has its own way of making a string representation of the underlying values. This default representation uses repr to show individual elements' values. Since in this case the array elements are unicode string, you see the 'u' in the output.
As a solution, what you want to do is to "unroll" the array manually and build up your own list representation. Here's one way of doing it:
for key, value in result.iteritems():
print key + ": " + ",".join(["'%s'" % v for v in value])
I believe this is what you're after
for key, value in result.iteritems():
print key + ": " + str([ str(v) for v in value ])
result = {u'Comments':[u'TM_FC', u'GT_FC', u'HG_FC', u'PO_FC', u'FU_FC']}
for k,v in result.iteritems():
print u'%s:%s' % (k,map(unicode.encode,v))
Simplified with string formatting, and map to change each value to a string, using the default encoding.

Categories