Reputation: 16469
If i enter in n
, a dictionary count_dict
of size n+1
will be created with keys 0...n
.
I want to parse through a list called binary_list
that contains strings of size n
that each compose of 0's or 1's. Each parse will count the number of 1's in the string and append
each string with the number of 1's to the appropriate key
ex:
{0:['000'], 1:['001','010','100'] , 2:['011', '101', '110'] , 3:['111']}
my code to perform this:
count_dict = dict.fromkeys(range(0,n+1))
for element in binary_list:
count_dict[element.count('1')].append(element)
error"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "facebook_prob.py", line 23, in sortbit
count_dict[element.count('1')].append(element)
AttributeError: 'NoneType' object has no attribute 'append'
Upvotes: 2
Views: 5850
Reputation: 369064
Without specifying the second argument, values are None by default. (See dict.fromkeys
)
>>> n = 3
>>> count_dict = dict.fromkeys(range(0,n+1))
>>> count_dict
{0: None, 1: None, 2: None, 3: None}
In addition to that, values created by dict.fromkeys
are shared by all entries.
>>> count_dict = dict.fromkeys(range(0,n+1), [])
>>> count_dict
{0: [], 1: [], 2: [], 3: []}
>>> count_dict[0] is count_dict[1]
True
collections.defaultdict
is more appropriate.
>>> from collections import defaultdict
>>> count_dict = defaultdict(list)
>>> count_dict[0].append('000')
>>> count_dict[1].append('001')
>>> count_dict[1].append('010')
>>> count_dict
defaultdict(<type 'list'>, {0: ['000'], 1: ['001', '010']})
Upvotes: 5