我有2个字典,一个将代码构建为bldg名称
Dct_1 = {'1': ['Bldg 1'], '2': ['Bldg 2'], '3': ['Bldg 3'], '4': ['Bldg 4'], '5': ['Bldg 5']...})
第二个将建筑代码与楼层和租户联系起来
Dct_2 = {'1': [('Floor 0', 'Ten 1'), ('Floor 1', 'Ten 2'), ('Floor 3', 'Ten 3')], '2': [('Floor 1', 'Ten A'), ('Floor 2', 'Ten B')...]}
我正在尝试编写一个函数来创建第3个dct,以将楼层和租户与bldg名称相关联。
bldg_floor_tenant_dct = {'Bldg 1': [('Floor 0', 'Ten 1'), ('Floor 1', 'Ten 2'), ('Floor 3', 'Ten 3')], 'Bldg 2': [('Floor 1', 'Ten A'), ('Floor 2', 'Ten B')] ...}
是我想要的。
我尝试过以下两个函数,第一个返回错误而第二个没有任何操作
bldg_floor_tenant_dct = {}
for facilities_code, building_name in Dct_1.iteritems():
floors = Dct_2[facilities_code]
for k(floor_num, floor_dept) in floors:
b_data = bldg_floor_tenant_dct.get(building_name, [])
b_data.append({floor_num: floor_num,
dept: floor_dept})
print bldg_floor_tenant_dct
错误:
File "<stdin>", line 3
SyntaxError: can't assign to function call
和第二个:
bldg_floor_tenant_dct = defaultdict(list)
for keys in Dct_1:
if Dct_1.keys() == Dct_2.keys():
bldg_floor_tenant_dct[Dct_1.values()].append(Dct_2.values())
print bldg_floor_tenant_dct
break
我缺少什么或者有更好的方式来写这个?
答案 0 :(得分:4)
你可以使用字典理解。缩短Dct_1
和Dct_2
的演示:
>>> Dct_1 = {'1': ['Bldg 1'], '2': ['Bldg 2']}
>>> Dct_2 = {'1': [('Floor 0', 'Ten 1'), ('Floor 1', 'Ten 2'), ('Floor 3', 'Ten 3')], '2': [('Floor 1', 'Ten A'), ('Floor 2', 'Ten B')]}
>>> {v[0]:Dct_2[k] for k,v in Dct_1.items()}
{'Bldg 2': [('Floor 1', 'Ten A'), ('Floor 2', 'Ten B')], 'Bldg 1': [('Floor 0', 'Ten 1'), ('Floor 1', 'Ten 2'), ('Floor 3', 'Ten 3')]}
答案 1 :(得分:1)
问题在于这一行:
for k(floor_num, floor_dept) in floors:
k(floor_num, floor_dept)
看起来像是python的一个函数,你不能以这种方式为函数赋值。而是尝试
for floor_num, floor_dept in floors:
答案 2 :(得分:1)
我不确定为什么,但你的解决方案似乎很复杂。我会这样写的:
Dct_1 = {'1': ['Bldg 1'], '2': ['Bldg 2'], '3': ['Bldg 3'], '4': ['Bldg 4'], '5': ['Bldg 5']}
Dct_2 = {'1': [('Floor 0', 'Ten 1'), ('Floor 1', 'Ten 2'), ('Floor 3', 'Ten 3')], '2': [('Floor 1', 'Ten A'), ('Floor 2', 'Ten B')]}
result = {}
for key, value in Dct_2.iteritems():
for item in value:
if key in Dct_1 and Dct_1[key]:
result[item] = Dct_1[key]
print result