--> Skip to main content

Featured

Steps to Create a Project on GitHub

Steps to create a project on GitHub:  1.   Start a repo on GitHub 2.   Make a README.md file 3.   Open vs code – new folder – new terminal – git clone http:…. (from the repo). 4.   In terminal – cd theprojectname   à move into the project file 5.   Ls -la is for showing hidden file à not working for me ???? 6.   Make some changes to README file, in terminal git status à shows all the changes on the file 7.   To add all changes update to the folder à git add . (the dot . means all changes to be added) 8.   Add a new file index.html, in terminal à git commit -m “title of commit” -m “description of commit” 9.   Then git push origin master 10.                 ****Initial a repo in local text editor à git init 11.                 After use git add . etc, when pus...

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)]



Popular Posts