from collections import OrderedDict
b= OrderedDict([('04-25', 5), ('04-23', 53), ('04-20', 3), ('04-2', 33)])
# b = OrderedDict()
c = OrderedDict([('04-20', 5), ('03-18', 53), ('03-13', 3), ('03-12', 133)])
b_data = OrderedDict()
for k , v in b.items()+c.items():
b_data.setdefault(k,[]).append(v)
f_data = OrderedDict()
for k1, v1 in b_data.iteritems():
if len(v1)==1:
f_data[k1]=v1[0],0
else:
f_data[k1]=v1[0],v1[1]
print f_data
我可以获得f_data的输出
OrderedDict([('04-25', (5, 0)), ('04-23', (53, 0)), ('04-20', (3, 5)), ('04-2', (33, 0)), ('03-18', (53, 0)), ('03-13', (3, 0)), ('03-12', (133, 0))])
但是在合并b和c项时,在f_data中,值[0]应为b值,值[1]应为c值。如果没有值,则为0。
如果b项为空,我们必须在值[0]中保留0,在值[1]中保留c项。
如果b和c具有相同的键合并及其值,如上所述。
我对上述数据的预期输出是,
OrderedDict([('04-25', (5, 0)), ('04-23', (53, 0)), ('04-20', (3, 5)), ('04-2', (33, 0)), ('03-18', (0, 53)), ('03-13', (0, 3)), ('03-12', (0,133))])
答案 0 :(得分:4)
这将为您完成这项工作:
from collections import OrderedDict
b = OrderedDict([('04-25', 5), ('04-23', 53), ('04-20', 3), ('04-2', 33)])
c = OrderedDict([('04-20', 5), ('03-18', 53), ('03-13', 3), ('03-12', 133)])
f_data = OrderedDict()
for key in b.keys() + c.keys():
if not f_data.has_key(key):
try:
val_b = b[key]
except KeyError:
val_b = 0
try:
val_c = c[key]
except KeyError:
val_c = 0
f_data[key] = (val_b, val_c)
print f_data
当我运行此代码时,我得到以下输出:
OrderedDict([('04-25', (5, 0)), ('04-23', (53, 0)), ('04-20', (3, 5)), ('04-2', (33, 0)), ('03-18', (0, 53)), ('03-13', (0, 3)), ('03-12', (0, 133))])