将值插入嵌套字典

时间:2014-10-17 15:13:01

标签: python list dictionary

我在Python中有一些嵌套的dict,需要一些帮助才能使我的代码完全正常工作。

首先是代码:

data = {}

def insertIntoDataStruct(country, state,job,count,dict):
    if country in dict:
         dict[country][state] = {job: count}
    elif country not in dict:
         dict[country] = {state: {job: count}}
    elif state not in dict[country]:
         dict[country] = {state: {job: count}}
    elif job not in dict[country][state]:
         dict[country][state][job] = count
    else:
         dict[country][state][job] += count


 insertIntoDataStruct("US", "TX", 1234, 1, data)
 insertIntoDataStruct("IN", "KERELA", 1234, 1, data)
 insertIntoDataStruct("IN", "KERELA", 1234, 1, data)
 insertIntoDataStruct("US", "TX", 12345, 1, data)
 insertIntoDataStruct("US", "MI", 1234, 1, data)
 insertIntoDataStruct("IN", "M", 1234, 1, data)

 print data

目前正在打印这个:

{'US': {'MI': {1234: 1}, 'TX': {12345: 1}}, 'IN': {'M': {1234: 1}, 'KERELA': {1234: 1}}}

它是一个外层的词典,国家,内部层面,州,内层,工作:计数

计数无法正常工作,因为KERELA 1234应该有2,然后它看起来正在做的是用字典中已有的任何状态替换最新的状态。例如TX 1234没有显示,因为它后来被TX 12345替换

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

你的功能需要一些修复,试试这个:

def insertIntoDataStruct(country, state,job,count,dict):
    if country not in dict:
         dict[country] = {state: {job: count}}
    elif state not in dict[country]:
         dict[country][state] = {job: count}
    elif job not in dict[country][state]:
         dict[country][state][job] = count
    else:
         dict[country][state][job] += count

这可能是你最初的意思,如果这个国家不存在,那么创造它,否则如果国家不存在,等等......

另一种方法是使用defaultdict

from collections import defaultdict, Counter
jobsdict = defaultdict(lambda: defaultdict(Counter))
jobsdict['US']['TX']['1234'] += 1
相关问题