arun chauhan
arun chauhan

Reputation: 684

Functioning of append in dictionary?

Please explain the use of append function in the following example:

Example 1:

new = {}
for (key, value) in data:
    if key in new:
        new[key].append( value )
    else:
        new[key] = [value]

and in example 2:

new = {}
for (key, value) in data:
    group = new.setdefault(key, []) 
    group.append( value )

Upvotes: 1

Views: 73

Answers (1)

poke
poke

Reputation: 387607

new is a dictionary, but the dictionary’s value are lists, which have the list.append() method.

In the loop, the dictionary is being filled with the values from data. Apparently, it is possible that there are multiple values for a single key. So in order to save that within a dictionary, the dictionary needs to be able to store multiple values for a key; so a list is being used which then holds all the values.

The two examples show two different ways of making sure that the dictionary value is a list when the key is new.

The first example explicitly checks if the key is already in the dictionary using key in new. If that’s the case, you can just append to the already existing list. Otherwise, you need to add a new list to the dictionary.

The second example uses dict.setdefault which sets a value if the key does not exist yet. So this is a special way of making sure that there’s always a list you can append the value to.

Upvotes: 1

Related Questions