Sam  Son

Sam Son

1583546477

Updating Dictionary in Python 3.9

Python 3.9 is under active development and scheduled to be released in October this year. On Feb 26, the development team released its alpha 4 version. One of the new features, relevant to almost all Python programmers, is the introducing of new merge (|) and update (|=) operators.

Let’s take a quick peek what this is in this article.

Dictionaries

Dictionaries, commonly known as dict, are one of the most important built-in data types in Python . This data type is a flexibly-sized collection of key-value pairs, and it’s best known for having a constant time for data lookup because of its hashing implementation.

Here are some common usages:

# Declare a dict
student = {'name': 'John', 'age': 14}

# Get a value
age = student['age']
# age is 14

# Update a value
student['age'] = 15
# student becomes {'name': 'John', 'age': 15}

# Insert a key-value pair
student['score'] = 'A'
# student becomes {'name': 'John', 'age': 15, 'score': 'A'}

Merging Dictionaries — Old Ways

Sometimes, we need to merge two dictionaries for further processing. Prior to the official release of 3.9, there are several ways we can do this. Suppose we have two dicts: d1 and d2. We want to create a new dict called d3, a union of d1 and d2. To illustrate what we shall do if there are some overlapping keys between the merging dicts, we have another dict d2a, which has an overlapping key with d1.

# two dicts to start with
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d2a = {'a': 10, 'c': 3, 'd': 4}

# target dict
d3 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Using the update() method

The first way is to use the dict’s method update(). The following code snippet shows you how to do it. Note that we’ll have to create a copy of d1 first, as the update() function will modify the original dict.

# create a copy of d1, as update() modifies the dict in-place
d3 = d1.copy()
# d3 is {'a': 1, 'b': 2}

# update the d3 with d2
d3.update(d2)
# d3 now is {'a': 1, 'b': 2, 'c': 3, 'd': 4}

When there are overlapping keys, we have to be more cautious regarding which values are to be kept. As you can see below, the dict that is passed as the argument in the update() method will “win” the game by having the value (i.e., 10) for the overlapping key (i.e., ‘a’).

d3 = d1.copy()
d3.update(d2a)
# d3 now is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# This is not the way that we want

d3 = d2a.copy()
d3.update(d1)
# d3 now is {'a': 1, 'c': 3, 'd': 4, 'b': 2}
# This is the way that we want

Unpacking dictionaries

The second way is to use the unpacking of the dictionaries. Similarly as the above method, “last seen wins” when there are overlapping keys.

# unpacking
d3 = {**d1, **d2}
# d3 is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# Not right

d3 = {**d2a, **d1}
# d3 is {'a': 1, 'c': 3, 'd': 4, 'b': 2}
# Good

Using dict(iterable, **kwarg)

One way to create a dict in Python is using the dict(iterable, **kwarg) method. Specifically relevant to the current topic is that when the iterable is a dict, a new dict will be created with the same key-value pairs. For the keyword arguments, we can pass another dict such that it will add the key-value pairs to the dict that is going to create. Note that this keyword argument dict will replace the value with the same key — something like “last seen wins.” Please see below for an example.

d3 = dict(d1, **d2)
# d3 is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Good, it's what we want

d3 = dict(d1, **d2a)
# d3 is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# Not right, 'a' value got replaced

One thing to note is that this method only works when the keyword argument dict has strings as their keys. Like below, a dict using an int as its key won’t work.

>>> dict({'a': 1}, **{2: 3})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: keywords must be strings
>>> dict({'a': 1}, **{'2': 3})
{'a': 1, '2': 3}

Merging Dictionaries — New Feature

In the latest release of Python 3.9.0a4, we can use the merging operator | to merge two dicts very conveniently. An example is given below. You may have noticed that when there are overlapping keys between these two dicts, the last seen wins, and this behavior is consistent with what we’ve seen above, such as the update() method.

# use the merging operator |
d3 = d1 | d2
# d3 is now {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# good

d3 = d1 | d2a
# d3 is now {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# not good

Related to this merge operator is the augmented assignment version, which operates in-place (i.e., update the left side dict). Essentially, it functions the same way as the update() method. The following code snippet shows you its usage:

# Create a copy for d1
d3 = d1.copy()

# Use the augmented assignment of the merge operator
d3 |= d2
# d3 now is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# good

d3 |= d2a
# d3 now is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# not good

Closing Thoughts

This article reviewed the new feature of merging and updating dictionaries in Python 3.9. There are several other new updates/improvements in several modules, such as asyncio, math, and os modules. See the official website for more information. I can’t wait to check them out in its official release in October!

Are you ready for Python 3.9? Stay tuned for a review of its new features when it is officially released!

Thank you for reading!

#python #python 3.9 #programming

What is GEEK

Buddha Community

Updating Dictionary in Python 3.9
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Ray  Patel

Ray Patel

1623077700

Working with Python dictionaries: a cheat sheet

Accessing, editing and looping through dictionary items

Dictionaries in Python are a collection of key-value pairs — meaning every item in the dictionary has a key and an associated value.

If we want to write down prices of some items in a grocery store, normally we will note them on a piece of paper like this:

eggs - 4.99
banana - 1.49
cheese- 4.5
eggplant - 2.5
bread - 3.99

In Python dictionary lingo, the name of each item is “key” and the associated price is “value” and they appear in pairs. We can represent the same in a Python dictionary data structure as follows:

{"eggs": 4.99,
"banana": 1.49,
"cheese": 4.5,
"eggplant": 2.5,
"bread": 3.99}

Notice the differences. In the dictionary

  • each key is within quotation marks because they are strings
  • the associated values are not quoted because they are numeric
  • keys and values are separated by a colon (:)
  • the items are comma-separated

#dictionary #python #artificial-intelligence #dictionaries #python dictionary #working with python dictionaries

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind

1602666000

How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips