Codingeek https://www.codingeek.com A Coders Home Sat, 11 Mar 2023 08:33:30 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.13 https://www.codingeek.com/wp-content/uploads/2021/08/logo_size_invert.png Codingeek https://www.codingeek.com 32 32 How do I check if a list is empty in Python? https://www.codingeek.com/python-examples/check-if-list-is-empty/ https://www.codingeek.com/python-examples/check-if-list-is-empty/#respond Tue, 14 Mar 2023 08:33:00 +0000 https://www.codingeek.com/?p=7222 Often, we need to check if a list is empty . in this Python example we will discuss some o the ways to create a dictionary from separate lists in Python. Some of the topics which will be helpful for understanding the program implementation better are: List in Python Function in Python 1. Using the […]

The post How do I check if a list is empty in Python? first appeared on Codingeek.

]]>
Often, we need to check if a list is empty . in this Python example we will discuss some o the ways to create a dictionary from separate lists in Python.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using the len() function

This function returns the number of elements in a list. If a list is empty, len() will return 0,

Now let’s implement a program to check if a list is empty.

fruits = []

if len(fruits) == 0:
  print("The list is empty")
else:
  print("The list is not empty")
Output
The list is empty

2. Using the not operator

The not operator is a logical operator that reverses the truth value of a boolean expression. If a list is empty, the boolean expression not fruits will evaluate to True.

Now lets implement the example again

fruits = []

if not fruits:
  print("The list is empty")
else:
  print("The list is not empty")
Output
The list is empty

3. Using the == operator

This operator compares two values and returns True if they are equal, and False otherwise.

fruits = []

if fruits == []:
  print("The list is empty")
else:
  print("The list is not empty")
Output
The list is empty

4. Using bool() operator

The bool() function returns the boolean value of an object. If a list is empty, bool(fruits) will return False.

fruits = []

if not bool(fruits):
  print("The list is empty")
else:
  print("The list is not empty")
Output
The list is empty

5. Conclusion

In this Python example, we discussed how to use the len() function, the not operator, the == operator, or the bool() function to check if a list is empty in Python.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post How do I check if a list is empty in Python? first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/check-if-list-is-empty/feed/ 0
How do I concatenate two lists in Python? https://www.codingeek.com/python-examples/concatenate-lists/ https://www.codingeek.com/python-examples/concatenate-lists/#respond Mon, 13 Mar 2023 08:33:00 +0000 https://www.codingeek.com/?p=7223 In this Python example we will discuss some to concatenate two lists in Python. Some of the topics which will be helpful for understanding the program implementation better are: List in Python Function in Python Dictionary in Python For loop in Python 1. Using the + operator One way to concatenate two lists in Python […]

The post How do I concatenate two lists in Python? first appeared on Codingeek.

]]>
In this Python example we will discuss some to concatenate two lists in Python.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using the + operator

One way to concatenate two lists in Python is to use the + operator. This operator combines the two lists into a new list that contains all the elements from both lists.

Here’s the code:

cars1 = ['Toyota', 'Honda', 'Nissan']
cars2 = ['BMW', 'Mercedes', 'Audi']

all_cars = cars1 + cars2
print(all_cars)
Output
['Toyota', 'Honda', 'Nissan', 'BMW', 'Mercedes', 'Audi']

2. Using the extend() method

extend() method adds all the elements from one list to another list. It modifies the original list and does not create a new list.

Here’s the code

cars1 = ['Toyota', 'Honda', 'Nissan']
cars2 = ['BMW', 'Mercedes', 'Audi']

cars1.extend(cars2)
print(cars1)
Output
['Toyota', 'Honda', 'Nissan', 'BMW', 'Mercedes', 'Audi']

3. Using the * operator

The * operator creates a new list that contains multiple copies of the original list.

Here’s the code

cars1 = ['Toyota', 'Honda', 'Nissan']
cars2 = ['BMW', 'Mercedes', 'Audi']

all_cars = cars1 * 2 + cars2 * 3
print(all_cars)
Output
['Toyota', 'Honda', 'Nissan', 'Toyota', 'Honda', 'Nissan', 'BMW', 'Mercedes', 'Audi', 'BMW', 'Mercedes', 'Audi', 'BMW', 'Mercedes', 'Audi']

4. Conclusion

In this Python example, we discussed how to concatenate two lists using the + operator, the extend() method, or the * operator.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post How do I concatenate two lists in Python? first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/concatenate-lists/feed/ 0
How to find the index of an item in a list in Python? https://www.codingeek.com/python-examples/find-index-of-item-in-list/ https://www.codingeek.com/python-examples/find-index-of-item-in-list/#respond Sun, 12 Mar 2023 08:33:00 +0000 https://www.codingeek.com/?p=7225 To perform certain index-based operations while programming we need to access the index of an element in the list. In this Python example we will discuss some o the ways to find the index of an item in a list in Python. Some of the topics which will be helpful for understanding the program implementation […]

The post How to find the index of an item in a list in Python? first appeared on Codingeek.

]]>
To perform certain index-based operations while programming we need to access the index of an element in the list. In this Python example we will discuss some o the ways to find the index of an item in a list in Python.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using the index() method

The index() method returns the index of the first occurrence of an item in a list and a ValueError is raised if the element is not found.

Now let’s implement a program to find the index of an item in a list in Python.

my_list = [1, 2, 3, 4, 5]
item = 3
index = my_list.index(item)
print(index)
Output
2

2. Using enumerate() function

The enumerate() function in Python takes an iterable as an argument and returns a tuple containing the index and the item at that index.

Here is an example.

my_list = [1, 2, 3, 4, 5]
item = 3
for i, val in enumerate(my_list):
  if val == item:
    index = i
    break
print(index)
Output
2

3. Using the bisect module

The bisect module in Python has bisect_left() function that can be used to find the index of an item in a sorted list.

Here is an example.

import bisect

my_list = [1, 2, 3, 4, 5]
item = 3
index = bisect.bisect_left(my_list, item)
print(index)
Output
2

4. Using for loop and range() function

You can create a range of indices that matches the length of the list and iterate over them. Then, you can use the current index to access the corresponding item in the list.

Here is an example.

countries = ['USA', 'Canada', 'UK', 'Germany', 'Japan']

for i in range(len(countries)):
  print(i, countries[i])
Output
0 USA
1 Canada
2 UK
3 Germany
4 Japan

4. Conclusion

In this Python example, we discussed the index() method, for loop, the enumerate() function, or the bisect module. to find the index of an item in a list in Python.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post How to find the index of an item in a list in Python? first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/find-index-of-item-in-list/feed/ 0
How to make a dictionary (dict) from separate lists of keys and values? https://www.codingeek.com/python-examples/how-to-make-a-dictionary-dict-from-separate-lists-of-keys-and-values/ https://www.codingeek.com/python-examples/how-to-make-a-dictionary-dict-from-separate-lists-of-keys-and-values/#respond Tue, 07 Mar 2023 12:00:00 +0000 https://www.codingeek.com/?p=7193 Often, we need to create a dictionary from separate lists of keys and values. in this Python example we will discuss some o the ways to create a dictionary from separate lists in Python. Some of the topics which will be helpful for understanding the program implementation better are: List in Python Function in Python […]

The post How to make a dictionary (dict) from separate lists of keys and values? first appeared on Codingeek.

]]>
Often, we need to create a dictionary from separate lists of keys and values. in this Python example we will discuss some o the ways to create a dictionary from separate lists in Python.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using zip() Function

One of the simplest ways to create a dictionary from separate lists is to use the zip() function. The zip() function returns an iterator that aggregates elements from each of the input iterables.

Now let’s implement a program to create a dictionary from 2 separate lists.

keys = ['One', 'Two', 'Three']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
print(my_dict)
Output
{'One': 1, 'Two': 2, 'Three': 3} 

2. Using a Dictionary Comprehension

We can use a dictionary comprehension to iterate over the keys and values lists simultaneously and create a dictionary.

Now lets implement the example again

keys = ['One', 'Two', 'Three']
values = [1, 2, 3]
my_dict = {keys[i]: values[i] for i in range(len(keys))}
print(my_dict)
Output
{'One': 1, 'Two': 2, 'Three': 3} 

There are other ways like using a for loop to add elements to the empty dictionary but honestly, these are the better ways than implementing using a for loop. So we will skip that example for now, but I would still recommend you to write the example using for loop only.


3. Conclusion

In this Python example, we discussed multiple ways to create a dictionary from separate lists of keys and values.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post How to make a dictionary (dict) from separate lists of keys and values? first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/how-to-make-a-dictionary-dict-from-separate-lists-of-keys-and-values/feed/ 0
How do I make a flat list out of a list of lists in Python? https://www.codingeek.com/python-examples/flat-list-from-list-of-lists/ https://www.codingeek.com/python-examples/flat-list-from-list-of-lists/#respond Tue, 07 Mar 2023 08:33:04 +0000 https://www.codingeek.com/?p=7226 Often, we end with a list of lists while programming and need to process every element or need a flat list out of it. in this Python example we will discuss some of the ways to make a flat list out of a list of lists in Python. Some of the topics which will be […]

The post How do I make a flat list out of a list of lists in Python? first appeared on Codingeek.

]]>
Often, we end with a list of lists while programming and need to process every element or need a flat list out of it. in this Python example we will discuss some of the ways to make a flat list out of a list of lists in Python.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using nested loops

One way to flatten a list of lists is to use nested loops. You can iterate over each element of the outer list, and for each element, iterate over its sub-list and append each item to a new list.

Now let’s implement a program to make a flat list out of a list of lists in Python

nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
flat_list = []
for sublist in nested_list:
  for item in sublist:
    flat_list.append(item)
print(flat_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

2. Using list comprehension

The same can be achieved via list comprehension i.e. flatten out list in a single statement.

nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

3. Using itertools.chain

The itertools module in Python provides a chain() function that takes multiple iterables as arguments and returns a single iterable that iterates over each item of the input iterables.

Here is the example.

import itertools

nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
flat_list = list(itertools.chain(*nested_list))
print(flat_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

4. Using the functools.reduce() function

The reduce() function in Python’s functools module takes a function and a sequence as arguments and applies the function cumulatively to the items of the sequence, from left to right. Here is the code.

import functools

nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
flat_list = functools.reduce(lambda x, y: x+y, nested_list)
print(flat_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

5. Conclusion

In this Python example, we discussed multiple ways to make a flat list out of a list of lists in Python.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post How do I make a flat list out of a list of lists in Python? first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/flat-list-from-list-of-lists/feed/ 0
Differences between dict.get(key) and dict[key] and which one to use? https://www.codingeek.com/python-examples/dict-get-vs-dict-key/ https://www.codingeek.com/python-examples/dict-get-vs-dict-key/#respond Mon, 06 Mar 2023 12:00:00 +0000 https://www.codingeek.com/?p=7192 When working with dictionaries, there are two ways to retrieve the value associated with a particular key: using the dict[key] syntax or using the dict.get(key) method. In this Python example, we will discuss the differences between these two approaches and analyse which one to use and when. Some of the topics which will be helpful […]

The post Differences between dict.get(key) and dict[key] and which one to use? first appeared on Codingeek.

]]>
When working with dictionaries, there are two ways to retrieve the value associated with a particular key: using the dict[key] syntax or using the dict.get(key) method. In this Python example, we will discuss the differences between these two approaches and analyse which one to use and when.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Retrieving Values with dict[key]

The dict[key] syntax retrieves the value associated with a given key in a dictionary. For example:

my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict['key1']
print(value)
Output
'value1'

If the key does not exist in the dictionary, this will raise a KeyError. To avoid this, we can use the in keyword to check if the key exists in the dictionary first:

my_dict = {'key1': 'value1', 'key2': 'value2'}
if 'key3' in my_dict:
  value = my_dict['key3']
else:
  value = None
print(value)
Output
None

2. Retrieving Values with dict.get(key)

With dict(key) we do not need to care about whether the key exists in the dictionary or not. If the key does not exist in the dictionary, dict.get(key) returns None instead of raising a KeyError. For example:

my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict.get('key3')
print(value)
Output
None

In addition to that we can also specify a default value to return if the key does not exist in the dictionary:

my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict.get('key3', 'codingeek')
print(value)
Output
codingeek

3. Conclusion

In summary, both dict[key] and dict.get(key) are useful approaches for retrieving values from dictionaries in Python. In general, using dict[key] is preferred when you know that the key exists in the dictionary and you want to retrieve its value. However, if you’re not sure whether the key exists in the dictionary or you want to handle the case where it doesn’t exist, dict.get(key) is a safer choice.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post Differences between dict.get(key) and dict[key] and which one to use? first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/dict-get-vs-dict-key/feed/ 0
How to Count the frequencies in a list using a dictionary in Python? https://www.codingeek.com/python-examples/count-frequencies-in-list-using-dictionary/ https://www.codingeek.com/python-examples/count-frequencies-in-list-using-dictionary/#respond Sun, 05 Mar 2023 12:18:08 +0000 https://www.codingeek.com/?p=7194 A dictionary can be used to count the frequencies of elements in the list. Python example we will discuss how to count the frequencies in a list using a dictionary in Python. Some of the topics which will be helpful for understanding the program implementation better are: List in Python Function in Python Dictionary in […]

The post How to Count the frequencies in a list using a dictionary in Python? first appeared on Codingeek.

]]>
A dictionary can be used to count the frequencies of elements in the list. Python example we will discuss how to count the frequencies in a list using a dictionary in Python.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Counting Frequencies Using a Dictionary

The keys in a dictionary must be unique, while values can be duplicated. We can use this property to count the frequencies of elements in a list by treating each element in the list as a key in a dictionary and incrementing its value for each occurrence.

Now let’s implement a program to count the frequencies of the elements in Python.

fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana', 'kiwi', 'apple']
fruit_freq = {}

for fruit in fruits:
  if fruit in fruit_freq:
    fruit_freq[fruit] += 1
  else:
    fruit_freq[fruit] = 1

print(fruit_freq)
Output
{'apple': 3, 'banana': 3, 'orange': 1, 'kiwi': 1}

For each fruit, we check if it is already a key in fruit_freq. If it is, we increment its value by 1 otherwise we add it to fruit_freq with a value of 1. Finally, we print fruit_freq to verify that the frequencies have been counted correctly.


2. Using the collections Module

The collections module in Python provides a built-in Counter class that can be used to count the frequencies of elements in a list. The Counter object automatically counts the frequencies of each element in the list.

Here’s an example:

from collections import Counter

fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana', 'kiwi', 'apple']
fruit_freq = Counter(fruits)

print(fruit_freq)
Output
Counter({'apple': 3, 'banana': 3, 'orange': 1, 'kiwi': 1})

3. Conclusion

In this Python example, we discussed multiple ways to count the frequencies in a list using a dictionary, one with a custom implementation and another using the Counter class.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post How to Count the frequencies in a list using a dictionary in Python? first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/count-frequencies-in-list-using-dictionary/feed/ 0
How to Convert a list of Tuples into Dictionary in Python? https://www.codingeek.com/python-examples/convert-list-of-tuples-into-dictionary/ https://www.codingeek.com/python-examples/convert-list-of-tuples-into-dictionary/#respond Fri, 03 Mar 2023 18:37:00 +0000 https://www.codingeek.com/?p=7196 A dictionary in Python is a collection of key-value pairs. Sometimes we may have a list of tuples, where each tuple represents a key-value pair, and we may want to convert it into a dictionary. In this Python example, we will discuss how to convert a list of tuples. Some of the topics which will […]

The post How to Convert a list of Tuples into Dictionary in Python? first appeared on Codingeek.

]]>
A dictionary in Python is a collection of key-value pairs. Sometimes we may have a list of tuples, where each tuple represents a key-value pair, and we may want to convert it into a dictionary. In this Python example, we will discuss how to convert a list of tuples.

Some of the topics which will be helpful for understanding the program implementation better are:

Example:

Input :  
people = [('John', 25), ('Jane', 30), ('Mike', 40)] 
Output : 
{
 "John" : 25,
 "Jane" : 30,
 "Mike" : 40
}

1. Using a for loop

We can create an empty dictionary and iterate through the list of tuples, adding each tuple to the dictionary as a key-value pair.

Now let’s implement a program to convert list of tuples to a dictionary using for loop.

# Using a for loop
people_dict = {}
people = [('John', 25), ('Jane', 30), ('Mike', 40)] 
for person in people:
    people_dict[person[0]] = person[1]
print(people_dict)
Output
{'John': 25, 'Jane': 30, 'Mike': 40}

2. Using dict constructor

This is a one-line implementation of the previous example. We will use list comprehension to iterate through the tuples and create a dictionary using the dict constructor

# Using dictionary comprehension
people = [('John', 25), ('Jane', 30), ('Mike', 40)] 
people_dict = dict((person[0], person[1]) for person in people)
print(people_dict)
Output
{'John': 25, 'Jane': 30, 'Mike': 40}

3. Using the zip() function

We can use zip() to combine the first elements of tuples into a list, and the second element of the tuples into a list, and then pass these lists to the dict() constructor.

# Using the zip() function
people = [('John', 25), ('Jane', 30), ('Mike', 40)] 
keys, values = zip(*people)
people_dict = dict(zip(keys, values))
print(people_dict)
Output
{'John': 25, 'Jane': 30, 'Mike': 40}

4. Conclusion

In this Python example, we have explored three different methods to convert a list of tuples into a dictionary in Python.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post How to Convert a list of Tuples into Dictionary in Python? first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/convert-list-of-tuples-into-dictionary/feed/ 0
How to Merge Two Dictionaries in Python https://www.codingeek.com/python-examples/merge-two-dictionaries/ https://www.codingeek.com/python-examples/merge-two-dictionaries/#respond Thu, 02 Mar 2023 12:00:00 +0000 https://www.codingeek.com/?p=7180 In this Python example we will discuss some of the ways to merge two dictionaries as this is one of the most common operations in Python. Some of the topics which will be helpful for understanding the program implementation better are: List in Python Function in Python Dictionary in Python 1. Using the update Method […]

The post How to Merge Two Dictionaries in Python first appeared on Codingeek.

]]>
In this Python example we will discuss some of the ways to merge two dictionaries as this is one of the most common operations in Python.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using the update Method

One of the easiest way to merge the dictionaries is to use update method. This method updates the first dictionary with the key-value pairs from the second dictionary.

Now let’s implement a program to merge dictionaries using update method. After emerging the result dictionary will have all the key values from both the initial dictionaries.

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

dict1.update(dict2)

print(dict1)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

2. Using Dictionary Unpacking (**) Operator

Another simple way is to use dictionary unpacking operator. This operator unpacks the key-value pairs from one dictionary and adds them to another dictionary.

Now let’s implement a program to merge dictionaries using dictionary unpacking operator operator.

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

merged_dict = {**dict1, **dict2}

print(merged_dict)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

3. Using the dict Constructor

The dict constructor can also be used to merge two dictionaries in Python. This method creates a new dictionary by combining the key-value pairs from two dictionaries.

Now let’s implement a program to merge dictionaries using dict constructor.

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

merged_dict = dict(dict1, **dict2)

print(merged_dict)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

4. Using the ChainMap Function

The ChainMap function from the collections module can also be used to merge two dictionaries in Python. This function creates a view of all the dictionaries in a list and allows you to access their key-value pairs as if they were a single dictionary.

Now let’s implement a program to merge dictionaries using ChainMap function.

from collections import ChainMap

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

merged_dict = ChainMap(dict1, dict2)

print(merged_dict)
Output
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})

5. Using the merge Method

The merge method from the dict class creates a new dictionary by combining the key-value pairs from two dictionaries.

Now let’s implement a program to merge dictionaries using merge method.

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

merged_dict = dict1.copy()
merged_dict.update(dict2)

print(merged_dict)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

4. Conclusion

In this Python example, we discussed multiple ways to merge two dictionaries. We explored five different methods for merging dictionaries, including using the update method, the ** operator, the dict constructor, the ChainMap function, and the merge method.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post How to Merge Two Dictionaries in Python first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/merge-two-dictionaries/feed/ 0
Given a dictionary and a character array, print all valid words that are possible in Python https://www.codingeek.com/python-examples/print-all-valid-possible-words/ https://www.codingeek.com/python-examples/print-all-valid-possible-words/#respond Wed, 01 Mar 2023 16:00:00 +0000 https://www.codingeek.com/?p=7195 In this Python example we will discuss the following problem statement. Given a dictionary of words and a character array, write a function that prints all valid words that are possible using characters from the array. A word is considered valid if it can be formed using only the characters from the array, and if […]

The post Given a dictionary and a character array, print all valid words that are possible in Python first appeared on Codingeek.

]]>
In this Python example we will discuss the following problem statement. Given a dictionary of words and a character array, write a function that prints all valid words that are possible using characters from the array. A word is considered valid if it can be formed using only the characters from the array, and if it is present in the dictionary.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using a for loop

We can iterate through each word in the dictionary and check if it can be formed using only the characters in the char_array. To check if a word can be formed using the characters in the array, we can convert the word and the array into sets and use the issubset() method to check if that is the subset of the character array.

Now let’s implement a program for this problem –

def print_valid_words(dictionary, char_array):
  for word in dictionary:
    if set(word).issubset(set(char_array)):
      print(word)

dictionary = {'cat', 'dog', 'act', 'god', 'bat'}
char_array = ['a', 'c', 't', 'o', 'g', 'd']
print_valid_words(dictionary, char_array)
Output
cat
god
dog
act

2. Using list comprehension

This is exactly like the previous example but instead of using a for loop we will use list comprehension to achieve the same.

Now let’s implement a program for this problem –

def print_valid_words(dictionary, char_array):
  valid_words = [word for word in dictionary if set(word).issubset(set(char_array))]
  print(valid_words)

dictionary = {'cat', 'dog', 'act', 'god', 'bat'}
char_array = ['a', 'c', 't', 'o', 'g', 'd']
print_valid_words(dictionary, char_array)
Output
['cat', 'god', 'dog', 'act']

3. Conclusion

In this Python example, we discussed how to print all valid words that can be formed using characters from a given character array, using a dictionary in Python. We explored two methods to solve this problem


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

The post Given a dictionary and a character array, print all valid words that are possible in Python first appeared on Codingeek.

]]>
https://www.codingeek.com/python-examples/print-all-valid-possible-words/feed/ 0