def positive(self):
total = {}
final = {}
for word in envir:
for i in self.lst:
if word in i:
if word in total:
total[word] += 1
else:
total[word] = 1
final = sorted(total, reverse = True)
return total
This returns
{'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}
I want to get this dictionary back to a dictionary that is in order. How do you I sort it and return a dictionary?
Dictionaries in Python have no explicit order (except in 3.6). There is no property of 'order' in a hash table. To preserve order in Python, use a list of tuples:
unordered = (('climate', 10,), ('ecosystem', 1)) # etc
Calling
sorted(unordered)
on the above will give it back with the 'key' being the first item in each individual tuple. You do not need to provide any other arguments tosorted()
in this case.To iterate, use
for x, y in z:
wherez
is the list.