Dictionary functions

I think it should be added a function of append() in ditionary :smiley:

Please provide your motivation for this idea.

What would append function do?
Why is the existing dictionary API not suitable?

1 Like

Hello, @SenkoFlash, and welcome to Python Software Foundation Discourse!

Would the append function add a key:value pair to the dictionary?

Please see 5. Data Structures: 5.5. Dictionaries. As exemplified in that document, we can just do this, which has worked quite well in terms of readability and simplicity:

tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127

As insertion order is guaranteed in modern Python what functionality is missing in following examples:

>>> spam = {1: 'a'}
>>> ham = {2: 'b'}
>>> spam | ham
{1: 'a', 2: 'b'}
>>> {**spam, **ham}
{1: 'a', 2: 'b'}
>>> spam.update(ham)
>>> spam
{1: 'a', 2: 'b'}
1 Like

@SenkoFlash, we hope this discussion has been helpful to you.

The document Built-in Types: Mapping Types — dict briefly describes functions, operators, and methods that are useful for working with Python dict (dictionary) objects. Unfortunately, that reference does not make it entirely obvious which ones are methods. The functions include list(d) and len(d), with d representing the dictionary that is passed to the function.

The first method to be presented in the listing is clear(). In order to call the methods that are listed, you would use dot notation. For example, to remove all items from a dictionary named trees, you would do this:

trees.clear()

Your original post that initiated this discussion suggests that you might be particularly interested in the update([other]) method. It can be used to add new items to a dictionary, or to replace values associated with keys that are already in the dictionary. The ordering of the dictionary is based on the order in which the keys were added to it. Items that introduce new keys are placed at the end of the dictionary in the ordering. However, when a value associated with an existing key is updated, the affected item remains in its current place within the ordering.