How can I access to an attribute from a dictionary? (Python) - 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)

Related

Can you find an item from a list from the item's name in python?

So I was wondering if it was possible to find an item from a list by it's name. I am working on a very simple programming language, and with variables, there are two lists:
var_name = []
variable_data = []
And I have created an algorithm for assigning variables to these lists if you enter a command to assign a variable. Here is the code:
if 'var:> ' in user_input:
varnames.append(user_input.replace('var:> ', "").split(', ', 1)[0])
variable_data.append(re.sub(r'.*, ', "", user_input))
And if you're wondering, the code in my language for making a variable is:
var:> var_name, var_data
But, coding things like printing and inputs do not support variables because I need to create some sort of translator that can get an item from a list from a string input. For example, if there was a variable named x in my programming language, can you make some sort of translator that finds the x item in the list from a string named x?
For example:
If you wanted to print a variable, or:
print:var> x
Is there a form to create some sort of translator that translates that x and takes it to the "x" item in the variable name list?
Also, I was considering using a dictionary for this, so if its easier, you could make a method for that too.
Thanks.
Try using dictionary. Its a map that translates key to its value. Key must be immutable value like string, and value can be any python data-type. Dictionary suits perfectly for your application.
dict = {}
if 'var:> ' in user_input:
key = user_input.replace('var:> ', "").split(', ', 1)[0]
value = re.sub(r'.*, ', "", user_input)
dict[key] = value
# dict = {'var_name':'var_data'}
To get data for x. Use regex to get x from your input. Then get from dictionary
key = re.search(r'var>(?P<key>.*)', d).group('key').strip()
value = dict.get(key, "Variable not defined yet")
# gives value of x if exist, else return "Variable not defined yet"

Python Max function - Finding highest value in a dictionary

My question is about finding highest value in a dictionary using max function.
I have a created dictionary that looks like this:
cc_GDP = {'af': 1243738953, 'as': 343435646, etc}
I would like to be able to simply find and print the highest GDP value for each country.
My best attempt having read through similar questions is as follows (I'm currently working through the Python crash course book at which the base of this code has been taken, note the get_country_code function is simply providing 2 letter abbreviations for the countries in the GDP_data json file):
#Load the data into a list
filename = 'gdp_data.json'
with open(filename) as f:
gdp_data = json.load(f)
cc_GDP` = {}
for gdp_dict in gdp_data:
if gdp_dict['Year'] == 2016:
country_name = gdp_dict['Country Name']
GDP_total = int(gdp_dict['Value'])
code = get_country_code(country_name)
if code:
cc_GDP[code] = int(GDP_total)
print(max(cc_GDP, key=lambda key: cc_GDP[key][1]))
This provides the following error 'TypeError: 'int' object is not subscriptable'
Note if leaving out the [1] in the print function, this does provide the highest key which relates to the highest value, but does not return the highest value itself which is what I wish to achieve.
Any help would be appreciated.
So you currently extract the key of the country that has the highest value with this line:
country_w_highest_val = max(cc_GDP, key=lambda key: cc_GDP[key]))
You can of course just look that up in the dictionary again:
highest_val = cc_GDP[contry_w_highest_val]
But simpler, disregard the keys completely, and just find the highest value of all values in the dictionary:
highest_val = max(cc_GDP.values())
How about something like this:
print max(cc_GDP.values())
That will give you the highest value but not the key.
The error is being cause because you need to look at the entire dictionary, not just one item. remove the [1] and then use the following line:
print(cc_GDP[max(cc_GDP, key=lambda key: cc_GDP[key])])
Your code currently just returns the dictionary key. You need to plug this key back into the dictionary to get the GDP.
You could deploy .items() method of dict to get key-value pairs (tuples) and process it following way:
cc_GDP = {'af': 1243738953, 'as': 343435646}
m = max(list(cc_GDP.items()), key=lambda x:x[1])
print(m) #prints ('af', 1243738953)
Output m in this case is 2-tuple, you might access key 'af' via m[0] and value 1243738953 via m[1].

Updating a dictionary with integer keys

I'm working on a short assignment where I have to read in a .txt file and create a dictionary in which the keys are the number of words in a sentence and the values are the number of sentences of a particular length. I've read in the file and determined the length of each sentence already, but I'm having troubles creating the dictionary.
I've already initialized the dictionary and am trying to update it (within a for loop that iterates over the sentences) using the following code:
for snt in sentences:
words = snt.split(' ')
sDict[len(words)]+=1
It gives me a KeyError on the very first iteration. I'm sure it has to do with my syntax but I'm not sure how else to update an existing entry in the dictionary.
When you initialize the dictionary, it starts out empty. The next thing you do is look up a key so that you can update its value, but that key doesn't exist yet, because the dictionary is empty. The smallest change to your code is probably to use the get dictionary method. Instead of this:
sDict[len(words)]+=1
Use this:
sDict[len(words)] = sDict.get(len(words), 0) + 1
The get method looks up a key, but if the key doesn't exist, you are given a default value. The default default value is None, and you can specify a different default value, which is the second argument, 0 in this case.
The better solution is probably collections.Counter, which handles the common use case of counting occurrences:
import collections
s = map(str.split, sentences)
sDict = collections.Counter(map(len, s))
defaultdicts were invented for this purpose:
from collections import defaultdict
sDict = defaultdict(int)
for snt in sentences:
sDict[len(snt.split())] += 1
If you are restricted to the use of pure dictionaries in the context of your assignment, then you need to test for existence of the key before incrementing its value in order to prevent a KeyError:
sDict = {}
for snt in sentences:
num_words = len(snt.split())
if num_words in sDict:
sDict[num_words] += 1
else:
sDict[num_words] = 1

Iterate through Python Dictionary without knowing the specific keys

I can't seem to figure out how to write this piece of Python Code.
I need to read something in from a file, which is this:
Jake FJ49FJH
Bob FJ49GKH
I've imported the file into a dictionary. I then check if the number plate (following the names) contains the sequence of two letters, two numbers, then three letters. Here is that part of the code:
d = {} # Blank Dictionary
with open("plates.txt") as f:
d = dict(x.rstrip().split(None, 1) for x in f) # Put file into dictionary
names = d.keys()
print(names)
#carReg = ??
a,b,c = carReg[:2],carReg[2:4],carReg[4:]
if all((a.isalpha(),b.isdigit(),c.isalpha(),len(c)== 3)):
print("Valid Reg")
else:
print("Invalid Reg")
# Now get the name of the person with the invalid carReg
As you can see, I don't know what to put for carReg. I need to loop through the dictionary, like in a list when you can use an integer to get part of the list. If the program returns Invalid Reg, then I need to get the key that the invalid reg belongs to - which will be a name.
Any help appreciated.
Iterate over dict.items(); it'll give you the (key, value) pairs from the dictionary:
for name, car_registration in d.items():

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