Converting Unicode Values as String from a Python Dictionary - python

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.

Related

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(' ', ''))

How can I access to an attribute from a dictionary? (Python)

so I have a Class Number with two string attributes called roman and text (It is supposed to store the Roman value and text description of an Arabic number)
I use a dictionary to store this information, the keys are the Arabic numbers and the values are instances of the class Number.
Finally, I want to print the attributes but I cannot find the way to access them.
Example:
number = Number("XX", "twenty")
dictionary {20:number}
So when I print the Arabic number and its roman value and tex description I want to get this output:
20 XX twenty
I thought that in order to get this I would have to code:
print("20 " + dictionary.get(20).roman + " " + dictionary.get(20).text)
But that is not the case, does someone know how to access the attributes of the object from a dictionary?
The proper way of accessing is storing the key and the value in temporary variables to be used in printing (or something else), rather than manually typing in 20.
k = 20 # key
v = dictionary[k] # value
roman, text = v.roman, v.text
If you want to do this in a loop (to print all elements),
for k in dictionary:
v = dictionary[k]
roman, text = v.roman, v.text
Or using dict.items(),
for k, v in dictionary.items():
print(k, v.roman, v.text)

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.

Python 2.7.8: Printing a sub-dictionary value?

I'm using ConfigParser which returns a dictionary of configuration data as such:
{'general': {'UserKey': 'thisisatestkey'}}
If I want to simply print the value of the UserKey key (in this case thisisatestkey), then I generally just do a print "Your key is: {0}".format(mydictvar.get('UserKey')).
If I just print out the raw dict to a string I get the above. If I use the print statement above I get result of None since there is no key in the root of the dict called UserKey. If I .get('general') I just get: {'UserKey': 'thisisatestkey'}
Obviously I could do a fore loop like so:
keydic = cp.get_config_data()
for m, k in keydic.iteritems():
for s, v in k.iteritems():
userkey = v
and then print userkey which works fine. But I want to know how I can just avoid having to do the entire for loop first and just print the darned value right inline? Thanks!
You can use
mydictvar['general']['UserKey']
Or, if keys might be missing
mydictvar.get('general', {}).get('UserKey')
mydictvar['general'] returns a dictionary object; you can then just apply [...] to that value to retrieve the next key.
This works in string formatting too:
>>> mydictvar = {'general': {'UserKey': 'thisisatestkey'}}
>>> print "Your key is: {0[general][UserKey]}".format(mydictvar)
Your key is: thisisatestkey
simply without loop:
>>> my_dict = {'general': {'UserKey': 'thisisatestkey'}}
>>> my_dict['general']['UserKey']
'thisisatestkey'

Does the d[key] operation always have to be used with .get()? [duplicate]

This question already has answers here:
Understanding .get() method in Python [duplicate]
(5 answers)
Closed 9 years ago.
I know d[key] will take the 'd' items and return them as keys, but if I only use d[key] I always get a keyerror. I've only seen it been used with .get(). For example I saw another question on here that I copied to study from:
myline = "Hello I'm Charles"
character = {}
for characters in myline:
character[characters] = character.get(characters, 0) + 1
print character
If you can use d[key] alone, could you give me some examples? Why wouldn't the above code work if I remove "character.get(characters, 0) + 1"?
The KeyError is raised only if the key is not present in the dict.
dict.get is interpreted as:
>>> print dict.get.__doc__
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
In your particular example, you're trying to calculate count of each character. As the dict is initially empty, so you need to set the key first before trying to fetch it's value and then add 1 to it.
So, character[characters] = character.get(characters, 0) + 1 can also be written as:
if characters in character: #if key is present in dict
character[characters] += 1
else:
character[characters] = 0 #if key is not present in dict, then set the key first
character[characters] += 1
So, you can see dict.get saves these steps, by returning the value of key if the key is present else return the default value 0.
But, for this example collections.Counter is the best tool.
dict.get(a,b) means if key a is not in dict, will return value b, else return the value of key a.
While d[key] get the value of key, but if key is not in dict it will raise a keyerror
The d.get(key, default) is the public accessor for a dictionary - it provides a mechanism for key missing.

Categories