w3resource

Python generating random ASCII OrderedDict

Python OrderedDict Data Type: Exercise-9 with Solution

Write a Python program that creates an OrderedDict and populates it with random integer values as values and their ASCII characters as keys. Print the OrderedDict.

Sample Solution:

Code:

import random
from collections import OrderedDict

def  random_ascii():
    return chr(random.randint(65, 90))

def main():
    ordered_dict = OrderedDict()

    for _ in range(10):
        key = random_ascii()
        value = random.randint(1, 50)
        ordered_dict[key] = value

    print("OrderedDict:", ordered_dict)

if __name__ == "__main__":
    main()

Output:

OrderedDict: OrderedDict([('Y', 43), ('B', 22), ('M', 9), ('D', 32), ('X', 27), ('N', 19), ('G', 19)])

In the exercise above, the "random_ascii()" function generates a random ASCII character using the "chr()" function and 'random.randint' to select a value within the ASCII range of uppercase letters (A-Z). The "main()" function creates an 'OrderedDict' and populates it with 10 random key-value pairs, where the key is a random ASCII character and the value is a random integer between 1 and 50. Finally, it prints the generated 'OrderedDict'.

Flowchart:

Flowchart: Python generating random ASCII OrderedDict.

Previous: Python Removing key-Value pair from OrderedDict.
Next: Python function for word lengths OrderedDict.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.