Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to list in a dictionary after setdefault [duplicate]

I have the below code where I am trying to append a 1 to the hash of an element, on every occurence of it in input.

def test(Ar):
    hash_table = {}
    for elem in Ar:
        if elem not in hash_table:
            hash_table.setdefault(elem,[]).append(1)
        else:
            hash_table[elem] = hash_table[elem].append(1)
    print(hash_table)

Ar = (1,2,3,4,5,1,2)
test(Ar)

Output:

{1: None, 2: None, 3: [1], 4: [1], 5: [1]}

Expected Output:

{1: [1,1], 2: [1,1], 3: [1], 4: [1], 5: [1]}

I am puzzled why None gets in on doing an append. Kindly explain what is happening.

Note:

On typing the else portion,

hash_table[elem] = hash_table[elem].append(1) # the append() was not suggested at all by the IDE. I forcibly put it, hoping things will work.
like image 328
KurinchiMalar Avatar asked Jan 15 '16 16:01

KurinchiMalar


People also ask

Can you append a list to a dictionary?

To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.

How do you add a list to an existing dictionary in Python?

By using ” + ” operator we can append the lists of each key inside a dictionary in Python. After writing the above code (Python append to the lists of each key inside a dictionary), Ones you will print “myvalue” then the output will appear as a “ {'Akash': [1, 3], 'Bharat': [4, 6]} ”.

How we can append items in existing dictionary?

Method 1: Using += sign on a key with an empty value In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary.


1 Answers

The list.append is an in-place operation. So it just modifies the list object and doesn't return anything. That is why, by default, None is getting returned from list.append and you are storing that corresponding to the key in this line

hash_table[elem] = hash_table[elem].append(1)

In your case, you don't need the if condition at all.

def test(Ar):
    hash_table = {}
    for elem in Ar:
        hash_table.setdefault(elem, []).append(1)
    print(hash_table)

because, setdefault will first look for the key elem in it and it found something, then it will return the value corresponding to it. And if it doesn't then it will create key elem and use the second argument passed to it as the value and then return then value.


Instead of using this, you can use collections.defaultdict, like this

from collections import defaultdict
def test(Ar):
    hash_table = defaultdict(list)
    for elem in Ar:
        hash_table[elem].append(1)
    print(hash_table)

This would do almost the same thing as the setdefault version


It looks like you are trying to find the frequency of elements. In that case you can simply use collections.Counter

from collections import Counter
Ar = (1, 2, 3, 4, 5, 1, 2)
print Counter(Ar)
# Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1})

This will give the number of times each and every element occurred in the iterable passed.

like image 64
thefourtheye Avatar answered Sep 23 '22 20:09

thefourtheye