Python Cyber Security - Generate password from a dictionary file
Python Cyber Security: Exercise-8 with Solution
Write a Python program that generates a password using a random combination of words from a dictionary file.
Content of the dictionary file (dictionary.txt) :
Pas1$Ku1 password password123 password123$ Password6#(% Germany#12 USA12^$# England0#
Sample Solution:
Python Code:
import random
def generate_password():
# Open dictionary file
with open('dictionary.txt') as f:
words = f.read().splitlines()
# Randomly select four words
password = random.sample(words, 4)
# Combine words with hyphens
password = '-'.join(password)
return password
# Example usage
password = generate_password()
print(password)
Sample Output:
USA12^$#-password123-England0#-password123$ password-England0#-Password6#(%-Pas1$Ku1 USA12^$#-password123-password123$-password
Explanation:
In the above exercise, we first open a dictionary file and read all the words. Then, we use the random.sample() function to randomly select four words from the list of words. Finally, we combine the words with hyphens to form the final password. You can adjust the number of words included in the password by changing the argument to random.sample().
Flowchart:

Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Check password strength and get suggestions.
Next: Program for simulating dictionary attack on password.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value:
Example:
def tips_map_values(obj, fn): ret = {} for key in obj.keys(): ret[key] = fn(obj[key]) return ret users = { 'Owen': { 'user': 'Owen', 'age': 29 }, 'Eddie': { 'user': 'Eddie', 'age': 15 } } print(tips_map_values(users, lambda u : u['age'])) # {'Owen': 29, 'Eddie': 15}
Output:
{'Owen': 29, 'Eddie': 15}
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook