When [] is passed as the second argument to dict.fromkeys(), all values in the resulting dict will be the same list object.

In Python 2.7 or above, use a dict comprehension instead:

Copydata = {k: [] for k in range(2)}

In earlier versions of Python, there is no dict comprehension, but a list comprehension can be passed to the dict constructor instead:

Copydata = dict([(k, []) for k in range(2)])

In 2.4-2.6, it is also possible to pass a generator expression to dict, and the surrounding parentheses can be dropped:

Copydata = dict((k, []) for k in range(2))
Answer from Sven Marnach on Stack Overflow
๐ŸŒ
Index.dev
index.dev โ€บ blog โ€บ initialize-dictionary-with-empty-lists-python
How to Initialize a Dictionary with Empty Lists in Python [with Examples]
Learn how to initialize a dictionary with empty lists in Python. This guide covers practical examples and common use cases for creating and managing dictionaries where each key is associated with an empty list.
Top answer
1 of 6
158

When [] is passed as the second argument to dict.fromkeys(), all values in the resulting dict will be the same list object.

In Python 2.7 or above, use a dict comprehension instead:

Copydata = {k: [] for k in range(2)}

In earlier versions of Python, there is no dict comprehension, but a list comprehension can be passed to the dict constructor instead:

Copydata = dict([(k, []) for k in range(2)])

In 2.4-2.6, it is also possible to pass a generator expression to dict, and the surrounding parentheses can be dropped:

Copydata = dict((k, []) for k in range(2))
2 of 6
127

Try using a defaultdict instead:

Copyfrom collections import defaultdict
data = defaultdict(list)
data[1].append('hello')

This way, the keys don't need to be initialized with empty lists ahead of time. The defaultdict() object instead calls the factory function given to it, every time a key is accessed that doesn't exist yet. So, in this example, attempting to access data[1] triggers data[1] = list() internally, giving that key a new empty list as its value.

The original code with .fromkeys shares one (mutable) list. Similarly,

Copyalist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print(data)

would output {0: [1, 2], 1: [1, 2]}. This is called out in the dict.fromkeys() documentation:

All of the values refer to just a single instance, so it generally doesnโ€™t make sense for value to be a mutable object such as an empty list.

Another option is to use the dict.setdefault() method, which retrieves the value for a key after first checking it exists and setting a default if it doesn't. .append can then be called on the result:

Copydata = {}
data.setdefault(1, []).append('hello')

Finally, to create a dictionary from a list of known keys and a given "template" list (where each value should start with the same elements, but be a distinct list), use a dictionary comprehension and copy the initial list:

Copyalist = [1]
data = {key: alist[:] for key in range(2)}

Here, alist[:] creates a shallow copy of alist, and this is done separately for each value. See How do I clone a list so that it doesn't change unexpectedly after assignment? for more techniques for copying the list.

Discussions

Why is it common in python to make an empty list or dict first?
In your case itโ€™s completely useless however many times we run a loop and append to a list or add to a variable counter or many such things. This has to exist before we do so. I mean I thought a lot of list comprehension was supposed to help mitigate this very thing lol. for element in some_list: my_list.append(element*2) Will fail. More on reddit.com
๐ŸŒ r/Python
157
165
September 19, 2023
Python: Adding an empty list as value to a dictionary - Stack Overflow
I want to append an empty list as the value when the name_input is not empty and grade_input is empty to a dictionary, whose keys are the name_input. The following is the code snippet. But it doesn't More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Create a list of empty dictionaries - Stack Overflow
-1 Python 3 - Initiating a list with multiple dictionaries ยท 0 Most efficient way to create a dictionary of empty lists in Python? More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to remove empty dictionary value from list?

Yes the quotes (empty string) are considered values and you would use an if statement. Probably what I would suggest is a list comprehension:

[d for d in mylist if d['name']]

This creates a new list with each dictionary value in there if the value corresponding to the key 'name' is not an empty string. The empty string is a Falsey value in Python, so instead of checking if d['name'] != '' (which is also totally valid) you can just ask if d['name'].

More on reddit.com
๐ŸŒ r/learnpython
27
39
January 28, 2019
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-initializing-dictionary-with-empty-lists
Initializing dictionary with Empty Lists in Python - GeeksforGeeks
July 11, 2025 - Dictionary comprehension is the most sought method to do this initialization. In this method, we create the no. of keys we require and then initialize the empty list as we keep on creating the keys, to facilitate the append operation afterward without an error. ... # Python3 code to demonstrate # to initialize dictionary with list # using dictionary comprehension # using dictionary comprehension to construct new_dict = {new_list: [] for new_list in range(4)} # printing result print ("New dictionary with empty lists as keys : " + str(new_dict))
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-initialize-list-with-empty-dictionaries
Python | Initialize list with empty dictionaries | GeeksforGeeks
March 24, 2023 - We can create a list containing single empty dictionary and then multiply it by Number that is size of list. The drawback is that similar reference dictionaries will be made which will point to similar memory location.
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ why is it common in python to make an empty list or dict first?
r/Python on Reddit: Why is it common in python to make an empty list or dict first?
September 19, 2023 -

Something I've never understood with python is why it is so common for an empty list to be created and then populated with something in a subsequent (or even more common next) line:

my_list = []
my_list = [i for i in range(1, 21)]

Obviously this is a really really toy example, but I'm consistently finding this in "production" code in multiple places. Is it pythonic? It's basically pure duplication so I doubt it. Is it some hacky "optimisation"? Is it a side effect of the code priorly being a for loop, then turned to a list comprehension but not tidied up right?

I honestly just feel ike I'm missing something key, with the amount of times and variety of places I see this pattern.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-check-if-dictionary-is-empty
Check if dictionary is empty in Python - GeeksforGeeks
July 11, 2025 - Check if the list is empty using the nsmallest() method of the heapq module with k=1 and a custom key ยท function that returns 0 for all elements. If the smallest element is not found, then the list is empty. Return the result.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ datastructures.html
5. Data Structures โ€” Python 3.14.6 documentation
A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
Find elsewhere
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ empty-dictionary-python
Create Empty Dictionary in Python (5 Easy Ways) | FavTutor
April 13, 2022 - A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces {}. ... In Python, we can create an empty dictionary by putting no elements ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-test-for-empty-dictionary-value-list
Python - Test for Empty Dictionary Value List - GeeksforGeeks
April 10, 2023 - Use the any() function with the values() method of the dictionary test_dict to check if any of the values in the dictionary are empty. Use the not keyword to negate the result of the any() function.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ how to create python empty dictionary?
How to Create Python Empty Dictionary? - Spark By {Examples}
May 31, 2024 - You can use the zip() and len() methods to create an empty dictionary with keys and no values. Python zip() is a built-in function that is used to zip or combine the elements from two or more iterable objects like lists, tuples, dictionaries, etc.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ initialize-an-empty-dictionary-in-python
Initialize an Empty Dictionary in Python - GeeksforGeeks
July 15, 2025 - This code demonstrates how to create an empty dictionary using a dictionary comprehension. It initializes d with no elements and then prints the dictionary, its length, and its type.
๐ŸŒ
Python Guides
pythonguides.com โ€บ how-to-create-an-empty-python-dictionary
Create an Empty Dictionary in Python
September 9, 2025 - Learn 4 easy ways to create an empty dictionary in Python with practical examples. Step-by-step guide for beginners and pros to use {}, dict(), and more.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to remove empty dictionary value from list?
r/learnpython on Reddit: How to remove empty dictionary value from list?
January 28, 2019 -

I have a list with dictionary objects in them like so:

[{'name':'test1'},{'name':''},{'name':'test2'}]

How do I check if the list has a empty dictionary value and remove said value so the new list looks like this:

[{'name':'test1'},{'name':'test2'}]

do I need an if statement for this? are the quotes considered values in the dictionary?

Top answer
1 of 3
24

Yes the quotes (empty string) are considered values and you would use an if statement. Probably what I would suggest is a list comprehension:

[d for d in mylist if d['name']]

This creates a new list with each dictionary value in there if the value corresponding to the key 'name' is not an empty string. The empty string is a Falsey value in Python, so instead of checking if d['name'] != '' (which is also totally valid) you can just ask if d['name'].

2 of 3
7

An alternative to creating a new list is to iterate backwards through the original list and selectively delete elements:

for i in range(len(mylist) - 1, -1, -1):
    if mylist[i]["name"] == "":
        del mylist[i]

This is useful for cases where you have other objects that refer to the original list, since it retains the original list (whereas binding the same variable name to a new list doesn't replace the original list in memory). This might be getting away from your original question, but here's an example to show what I mean:

>>> x = [1, 2, 3]    # original list
>>> y = [x, 'a', 'b']    # another object that refers to the original list
>>> print(y)
[[1, 2, 3], 'a', 'b']
>>> x.append(4)    # modify the original list
>>> print(y)    # demonstrate that the change is reflected in the object that references the list
[[1, 2, 3, 4], 'a', 'b']
>>> del x[1]    # modify the original list by deleting an element
>>> print(x)
[1, 3, 4]
>>> print(y)    # again, show that the change is reflected in the other object
[[1, 3, 4], 'a', 'b']
>>> x = [num for num in x if num > 2]    # bind variable name x to a new list using a comprehension
>>> print(x)
[3, 4]
>>> print(y)    # show that the reference in y still refers to the old list, which is no longer bound to a variable
[[1, 3, 4], 'a', 'b']

Just something to keep in mind.

๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
Add the ability to declare an empty dict as `{:}` - Ideas - Discussions on Python.org
March 27, 2023 - In my opinion, the fact that {} declares an empty dict is a major design flaw. Empty curly braces should only be associated with the empty set. If a newcomer learns that [] declares an empty list, their intuition would be to do the same thing for a set. Instead, they have to use set(). This is very counter-intuitive.
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-empty-dictionary
How to create Empty Dictionary in Python?
You can create an empty dictionary in Python using initialization and dict() constructor. Provide no key:value pairs during initialization and no arguments to dict() constructor, in which both cases, returns an empty dictionary.