Can someone explain this to me, and/or direct me on the right/pythonic way of doing this?
Python 2.7.
Ultimately, I am trying to loop through dictionary countsD:
countsD = {"aa": None, "bb": None, "cc": None, "dd": None}
and for the match in a corresponding dictionary d:
d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45, 98), "dd": (1, 33)}
add the count of items as a value to the corresponding matching key, to create finally this countsD
{"aa": 6, "bb": 3, "cc": 2, "dd": 2}
If I do this with the above
> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45, 98), "dd": (1, 33)}
> for key in d:
>> print(key)
>> print(len(d[key]))
Returned is this, which is what I want
aa
6
cc
2
dd
2
bb
3
HOWEVER, if one of the values for a key only contains 1 value (entirely possible), like (see "cc"):
d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45), "dd": (1, 33)}
and then run the same for loop, I get an error on the "cc" key:
aa
6
cc
Traceback (most recent call last):
File "<interactive input>", line 3, in <module>
TypeError: object of type 'int' has no len()
HOWEVER again, if I make that "cc" key have an empty value (), then all is fine again.
d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}
>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}
>>> for key in d:
... print(key)
... print(len(d[key]))
...
aa
6
cc
0
dd
2
bb
3
And in typing the title for this post just now, I was referred to Count number of values in dictionary for each key for an answer. Great, one line! But again, for a key with just one value, it fails. This good:
>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}
>>> new_countsD = {k: len(v) for k,v in d.items()}
>>> new_countsD
{'aa': 6, 'bb': 3, 'cc': 0, 'dd': 2}
this not, see key "cc"
>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (111), "dd": (1, 33)}
>>> new_countsD = {k: len(v) for k,v in d.items()}
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 1, in <dictcomp>
TypeError: object of type 'int' has no len()
So, what gives?? I feel like I am missing something stupid...
Thanks for any help!