Featured
- Get link
- X
- Other Apps
Python Practice : To Sort a Dictionary by its Values Using String and Random Modules
Random module in Python is very interest to play with, let's see what we can do with this little project.
What to achieve:
To use Random methods to create 10 random words with random number of length of alphabets, such as (ced,sghe,d,ewgt....)
Then create a dictionary with 0 through 9 in random order as keys, and the 10 random words as values.
The outcome is to print out a sorted dictionary by values.
Let's see the code below:
import string
import random
keys= list(range(0, 10))
random.shuffle(keys)
print(f'1 {keys}')
values = string.ascii_lowercase
dict_first= {}
for key in keys:
word = "".join(random.sample(values,random.randint(1, 5)))
dict_first[key] = word
print(f'2 {dict_first}')
print(f'3 {sorted(dict_first)}')
print(f'4 {sorted(dict_first.items())}')
dict_second={}
for k,v in dict_first.items():
dict_second[v] = k
print(f'5 {sorted(dict_second)}')
print(f'6 {sorted(dict_second.items())}')The output is like this:
1 [1, 5, 9, 3, 2, 0, 4, 7, 8, 6]
2 {1: 'xvh', 5: 'onwaj', 9: 'mfq', 3: 'qkwsx', 2: 'gqrc', 0: 'f', 4: 'xhkgc', 7: 'd', 8: 'egh', 6: 'tvm'}
3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4 [(0, 'f'), (1, 'xvh'), (2, 'gqrc'), (3, 'qkwsx'), (4, 'xhkgc'), (5, 'onwaj'), (6, 'tvm'), (7, 'd'), (8, 'egh'), (9, 'mfq')]
5 ['d', 'egh', 'f', 'gqrc', 'mfq', 'onwaj', 'qkwsx', 'tvm', 'xhkgc', 'xvh']
6 [('d', 7), ('egh', 8), ('f', 0), ('gqrc', 2), ('mfq', 9), ('onwaj', 5), ('qkwsx', 3), ('tvm', 6), ('xhkgc', 4), ('xvh', 1)]
- Get link
- X
- Other Apps
Popular Posts
Floating Label Animation in Form Using Tailwind CSS Peer Marker and Placeholder Shown Modifier
- Get link
- X
- Other Apps
Python Sqlite3 Database Management - Create Email Database and Sort Emails
- Get link
- X
- Other Apps