Changes

Jump to navigation Jump to search
733 bytes added ,  10:39, 6 April 2015
Line 109: Line 109:  
True
 
True
 
</source>
 
</source>
This can be used to sort dictionaries by keys.
+
'''To sort dictionaries by keys.'''
 
<source lang="python">
 
<source lang="python">
 
>>> d = {'c':22, 'b':1, 'a':10}
 
>>> d = {'c':22, 'b':1, 'a':10}
Line 119: Line 119:  
[('a', 10), ('b',1), ('c', 22)]
 
[('a', 10), ('b',1), ('c', 22)]
 
</source>
 
</source>
 +
'''To sort by value:'''
 +
<source lang="python">
 +
c = {'c':22, 'b':1, 'a':10}
 +
tmp = list()
 +
for k, v in c.items():
 +
    tmp.append( (v, k) )
 +
tmp.sort(reverse = True)
 +
print tmp
 +
[(22, 'c'), (10, 'a'), (1, 'b')]
 +
</source>
 +
'''The same sort by value with list comprehension'''
 +
<source lang="python">
 +
c = {'c':22, 'b':1, 'a':10}
 +
print sorted( [ (v,k) for k,v in c.items() ] )
 +
</source>
 +
<br />
 +
'''Top 10 most common words.'''
 +
<source lang="python">
 +
fhand = open('romeo.txt')
 +
counts = dict()
 +
for line in fhand:
 +
    words = line.split()
 +
    for word in words:
 +
        counts[word] = counts.get(word, 0) +1
 +
lst = list()
 +
for key, val in counts.items():
 +
    lst.append((val, key))
 +
lst.sort(reverse = True)
 +
for val, key in lst[:10]
 +
    print key, val
 +
</source>
 +
 
==== Dictionary ====
 
==== Dictionary ====
 
Key - Value pairs. They are called diferent in diferent languages:<br />
 
Key - Value pairs. They are called diferent in diferent languages:<br />

Navigation menu