Other answers already adressed why this fails, here is a convenient solution that sets a default for if the key is not already present, such that your appending does not fail. The way I read it, you want a dictionary with lists of other dictionaries as values. Imagining a situation such as

Copysomedict = {}
somevar = 0
somevar_name = str(somevar)

key1 = "oh"
value1 = 1

You can do

Copysomedict.setdefault(somevar_name,[]).append({key1,value1})

This will evaluate to

{'0': [{'oh', 1}]}

In other words, change lines of this sort

Copysomedict[some_variables_name] += [{ 'somekey': somevalue }]

Into:

Copysomedict.setdefault(some_variables_name,[]).append({'somekey':somevalue})

I hope this answers your question.

Answer from Banana on Stack Overflow
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to Create Empty Dictionary in Python and add Items? Python Dictionary Tutorial #14 - YouTube
Learn how to create an empty Dictionary in Python and add key-value pairs to it later#pythontutorial #python #pythonprogramming #python3 #pythonforbeginners ...
Published ย  July 15, 2023
Discussions

Appending elements to an empty dictionary of lists in Python - Stack Overflow
In other words, I have an empty dictionary, and as I read in values one by one from a file, I would like to append them one by one to a given dictionary key (which may or may not exist already). The challenge is that I can't create the list at once. I can only append values one by one, but I'm not sure how I can tell Python that I want a dictionary of lists when I add ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
numpy - How to add an empty item in a dictionary in python? - Stack Overflow
I don't see why you want to add an entry that has an array key. None of the other keys are arrays. And as you found out an array can't be a key. ... vectorize passes scalar values from the argument to your function. It does not pass an array. So there's no point to having an array, empty or not, as a key. Whether np.vectorize is the best tool for using this dictionary ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Adding Key: Value to Empty Dictionary via For Loop
dictionary keys are "unique" - so you are overwriting the previous entry each time. >>> quotes = {} >>> quotes['author'] = 'quote1' >>> quotes {'author': 'quote1'} >>> quotes['author'] = 'quote2' >>> quotes {'author': 'quote2'} Perhaps you want a list of dicts? [ { 'author': 'quote1' }, { 'author': 'quote2' }, ... ] More on reddit.com
๐ŸŒ r/learnpython
6
1
December 3, 2022
I want to add a new key-value-pair to a Dict. I can't figure out why it doesn't work

Try

a = Dict{String, Array{Int64,1}}()

push!(a, "sdf" => [1, 2])

The only difference are the empty parentheses, initializing an empty dictionary. It seems to work on my machine

More on reddit.com
๐ŸŒ r/Julia
11
4
November 6, 2018
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ adding key: value to empty dictionary via for loop
r/learnpython on Reddit: Adding Key: Value to Empty Dictionary via For Loop
December 3, 2022 -

Over the years I've collected a lot of quotes and I am trying to write a script to parse them out into a dictionary so I can use them in another script.

The quotes are always in this format:

> [!quote] Quote by [[Robert Greene]]
> Cultivate a fearless approach to life, attack everything with boldness and energy.

So I've created this script to get them and add them to a dictionary:

import re

quote_list = {}

with open('Quotes.md', 'r', encoding='UTF8') as file:
    for line in file:
        if '[!quote]' in line:
            author = re.findall(r'\[\[(.*?)]]', line) # Find [[author]]
            author = ' '.join(author) # remove []
            quote_list['author'] = author # add to dictionary
        elif '>' in line and not '[!quote]' in line:
            quote = line.strip('> ').strip('\n') # strip off > and \n
            quote_list['quote'] = quote

print(quote_list)

However, the final result is only 1 quote (the last quote in the document), so it appears to be overwriting the entry each time. I'm at a loss for what I'm doing wrong so any advice is much appreciated.

As I typed this out I realized that I don't think this is going to keep the authors + quotes together like I had hoped.

Example:

{'author': 'Frank A. Clark', 'quote': "We find comfort among those who agree with us - growth among those who don't"}

Update: This is the final solution I landed on. Reading line by line, if the line meets my criteria then I do what I need to for the author and then use next(file) to skip to the next line and pull the quote, finally adding it into a list as a separate dictionary.

https://pastebin.com/nuiT8Nry

๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries_add.asp
Python - Add Dictionary Items
Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge Python If...Else
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ how to add items to a python dictionary
How to Add Items to a Python Dictionary - Spark By {Examples}
May 31, 2024 - Python provides various ways to add items or elements to a dictionary. Dictionaries are mutable, so we can add, delete, and update the dictionaries. In
๐ŸŒ
Esri Community
community.esri.com โ€บ t5 โ€บ python-questions โ€บ appending-data-to-an-empty-dictionary โ€บ td-p โ€บ 567277
Solved: Appending data to an empty dictionary - Esri Community
December 12, 2021 - The field that I want the data from to append to the dictionary is called 'NAME' in the hubFeatures FC. I was thinking of using cursors to achieve this. Unless there is an alternative approach. The idea is to then use the items in the dictionary to apply a query to the necessary layers and complete the functionality of the tool using a for loop.
Find elsewhere
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ python-empty-dictionary-and-appending
Python Empty Dictionary and Appending: A Comprehensive Guide - CodeRivers
February 22, 2026 - Here, new_dict is an empty dictionary initially. The update() method takes another dictionary (new_data in this case) and adds all its key-value pairs to new_dict.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ create-a-dictionary-in-python-python-dict-methods
Create a Dictionary in Python โ€“ Python Dict Methods
March 14, 2022 - New items can be added, already ... and items can be deleted. To add a key-value pair to a dictionary, use square bracket notation. ... First, specify the name of the dictionary. Then, in square brackets, create a key and assign it a value.
๐ŸŒ
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.
๐ŸŒ
Great Learning
mygreatlearning.com โ€บ blog โ€บ it/software development โ€บ python dictionary append: how to add key/value pair?
Python Dictionary Append: How To Add Key/Value Pair?
October 14, 2024 - Yes, you can. When you use the update() method to append dictionary python, existing keys are updated with new values, but if there are any new keys, they are added to the dictionary without overwriting existing ones.
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-add-to-dictionary
Learn Python: How To Add to Dictionary (With Examples)
January 30, 2024 - The update() method is a powerful tool for adding multiple items to a dictionary or updating an existing item. However, itโ€™s important to remember that if a key in the dictionary youโ€™re updating matches a key in the dictionary youโ€™re adding, the value of the key in the original dictionary will be replaced with the value from the new dictionary. This behavior is consistent with the rule that keys in a Python dictionary must be unique.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ initialize-an-empty-dictionary-in-python
Initialize an Empty Dictionary in Python - GeeksforGeeks
April 12, 2025 - You can add, update or remove key-value pairs in a dictionary which makes it a flexible and dynamic data structure.What Does It Mean for Dictionaries to Be Mutable?Being mutabl ... A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets.Example:Pythona = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value assosiated with "geeks" x = a["geeks"] print
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-create-an-empty-dictionary-in-python
How to create an empty dictionary in Python?
March 24, 2026 - Empty dictionary: {} After adding values: {'name': 'Alice', 'age': 25} The dict() constructor creates an empty dictionary when called without arguments. ... dict1 = dict() print("Empty dictionary:", dict1) dict1['colors'] = ["Blue", "Green", ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ adding-items-to-a-dictionary-in-a-loop-in-python
Adding Items to a Dictionary in a Loop in Python - GeeksforGeeks
July 23, 2025 - res.update({i: j}) adds each key-value pair to the res dictionary. ... This method involves directly assigning values to the dictionary keys by iterating through both the keys and values. We can use a loop to access each key and then use the index to retrieve the corresponding value from a separate list. ... a = ['Name', 'Website', 'Topic', 'Founded'] b = ['GeeksforGeeks', 'https://www.geeksforgeeks.org/', 'Programming', 2009] res = {} # initializes an empty dictionary for i in range(len(a)): res[a[i]] = b[i] print(res)
๐ŸŒ
Guru99
guru99.com โ€บ home โ€บ python โ€บ python dictionary append: how to add key/value pair
Python Dictionary Append: How to Add Key/Value Pair
August 13, 2025 - We can make use of the built-in function append() to add elements to the keys in the dictionary.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-add-to-dictionary
How to Add and Update Python Dictionaries Easily | DigitalOcean
October 16, 2025 - If overwrite is True, update all keys (like dict.update()). """ if overwrite: dict1.update(dict2) else: for key, value in dict2.items(): if key not in dict1: dict1[key] = value return dict1 ยท This pattern prevents accidental overwriting of important data by controlling how updates are applied. Problem: Dictionaries often contain nested dictionaries (dictionaries as values).
๐ŸŒ
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 - # Quick examples of create empty dictionary # Example 1: Create an empty dictionary using {} curly braces my_dict = {} print("Empty dictionary:", my_dict) # Example 2: Create an empty dictionary using dict() my_dict = dict() print("Empty ...
Top answer
1 of 1
1

Look at your dicitonary:

In [21]: dd = dict(zip(numpy.arange(5), numpy.arange(5)*10))
In [22]: dd
Out[22]: {0: 0, 1: 10, 2: 20, 3: 30, 4: 40}

the keys are numbers. The same thing can be produced without numpy:

In [23]: dict(zip(range(5), range(0,50,10)))
Out[23]: {0: 0, 1: 10, 2: 20, 3: 30, 4: 40}

Your vectorize array access:

In [29]: y = np.vectorize(lambda x: dd[x], otypes=[int])
In [30]: y([0,1,3])
Out[30]: array([ 0, 10, 30])
In [31]: y([])
Out[31]: array([], dtype=int64)

I added the otypes so that the [] works.

I don't see why you want to add an entry that has an array key. None of the other keys are arrays. And as you found out an array can't be a key.

dictionary[np.array([], dtype='int64')]

vectorize passes scalar values from the argument to your function. It does not pass an array. So there's no point to having an array, empty or not, as a key.

Whether np.vectorize is the best tool for using this dictionary is another question. Usually it doesn't improve speed over iterative access. Using a dictionary might the underlying problem, since it can only be accessed on key at a time.

===

Without the otypes, vectorize raises an error

ValueError: cannot call `vectorize` on size 0 inputs unless `otypes` is set

vectorize makes a trial call to the function to determine the return dtype.

===

Here's a more robust version of your y, one that won't choke on a missing key:

In [32]: y = np.vectorize(lambda x: dd.get(x,-100), otypes=[int])
In [33]: y([1,2,3,10])
Out[33]: array([  10,   20,   30, -100])
๐ŸŒ
Sanfoundry
sanfoundry.com โ€บ python-program-add-key-value-pair-dictionary
Python Program to Add a Key-Value Pair to the Dictionary - Sanfoundry
May 30, 2022 - This is a Python Program to add a key-value pair to a dictionary. ... The program takes a key-value pair and adds it to the dictionary. ... 1. Take a key-value pair from the user and store it in separate variables. 2. Declare a dictionary and initialize it to an empty dictionary.