Dict KeyError for value in the dict

前端 未结 4 1794
Happy的楠姐
Happy的楠姐 2021-01-20 02:02

I have a dict inside a dict:

{
\'123456789\': {u\'PhoneOwner\': u\'Bob\', \'Frequency\': 0},
\'98765431\': {u\'PhoneOwner\': u\'Sarah\', \'Frequency\': 0},
         


        
4条回答
  •  -上瘾入骨i
    2021-01-20 02:18

    Not sure why you might be seeing that without more information - perhaps run in the interpreter and print out (a small) example output? In any event, something that I've found that helps in those cases is defaultdict Which will make a key with an object type of your choosing. It's a little off-base for this example, since you don't have homogeneous value-types (certainly not a requirement, but makes the most sense when using a defaultdict):

    from collections import defaultdict
    phoneNumberDict = defaultdict(lambda: defaultdict(int))
    phoneNumber[int(vline)]["Frequency"] += 1
    

    That said, for such a structure, I would think an object would be easier to keep track of things.

提交回复
热议问题