Home > Backend Development > Python Tutorial > How Can I Avoid Shared References When Using Python's `fromkeys` Method?

How Can I Avoid Shared References When Using Python's `fromkeys` Method?

Susan Sarandon
Release: 2024-12-14 20:25:18
Original
859 people have browsed it

How Can I Avoid Shared References When Using Python's `fromkeys` Method?

Understanding the fromkeys Method and its Limitations

When initializing a dictionary using the fromkeys method, it is important to be aware of its behavior with single-element arguments. Passing a list as the second argument will result in all dictionary values referencing the same list object.

Avoiding Unintended Sharing: Alternative Approaches

To prevent unintended sharing of values, consider using alternative methods:

  • Dict Comprehension (Python 2.7 ):

    data = {k: [] for k in range(2)}
    Copy after login
  • List Comprehension with Dict Constructor:

    data = dict([(k, []) for k in range(2)])
    Copy after login
  • Generator Expression with Dict (Python 2.4-2.6):

    data = dict((k, []) for k in range(2))
    Copy after login

Simple Example: Adding a Value to a Specific Key

The following code demonstrates the intended behavior:

data = {0: [], 1: []}
data[1].append('hello')
print(data)
# Output: {0: [], 1: ['hello']}
Copy after login

By using one of the suggested methods, you can initialize a dictionary of empty lists and modify individual key values without affecting the others.

The above is the detailed content of How Can I Avoid Shared References When Using Python's `fromkeys` Method?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template