Geek Logbook

Tech sea log book

Creating a Dictionary from a Word and a List in Python

In Python, creating and manipulating dictionaries is a common task. In this post, we’ll walk through a simple example of how to write a function that takes a word and a list, and returns a dictionary with the word as the key and the list as the value.

The Task

We have two pairs of data:

  • The word “home” and the list [1, 2, 3, 4, 5].
  • The word “roof” and the list [4, 5, 7, 6, 2].

Our goal is to create a function that receives a word and a list and returns a dictionary with the word as the key and the list as the value.

Step-by-Step Solution

1. Define the Function

We’ll start by defining a function named create_dictionary that takes two parameters: word and num_list.

def create_dictionary(word, num_list):
    dictionary = {word: num_list}
    return dictionary

2. Test the Function

Next, we’ll test our function with the given data. Let’s create two test cases:

word1 = "home"
list1 = [1, 2, 3, 4, 5]
word2 = "roof"
list2 = [4, 5, 7, 6, 2]

dict1 = create_dictionary(word1, list1)
dict2 = create_dictionary(word2, list2)

print(dict1)
print(dict2)

When you run this code, you should see the following output:

{'home': [1, 2, 3, 4, 5]}
{'roof': [4, 5, 7, 6, 2]}

3. Generalizing the Function

The create_dictionary function is quite flexible and can be used with any word and list. Here’s how you can define and use the function more generally:

def create_dictionary(word, num_list):
    return {word: num_list}

# Example usage
word = input("Enter a word: ")
num_list = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))
dictionary = create_dictionary(word, num_list)
print(f"Dictionary created: {dictionary}")

4. Conclusion

This simple function demonstrates how to create a dictionary with a word and a list in Python. It’s a useful technique for organizing data, and you can expand on it by adding more functionality, such as input validation or processing the list in some way.

Tags: