如何使用python在字典中展平和合并值?

时间:2013-03-14 07:36:13

标签: python list dictionary

我有这样的字典:

d = {'Date' : ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'],
     'Country Code' : ['93', '92', '91', '90'],
     'Area Code' : ['1,2,3,4,5,6,7', '31,32,43,44,54,56,7, ', '434,34,4', '00, 89']}

我想要一本这样的字典:

d = {'Date' : ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'],
     'Combined Code' : ['931,932,933,934,935,936,937', '9231,9232,9243,9244,9254,9256,927,92 ,', '91434,9134,914', '9000, 9089']}

我试过的是:

list(chain(*(product(*(s.split(",") for s in e)) for e in zip(*d.values()))))

但无法在字典中管理这一切。

2 个答案:

答案 0 :(得分:2)

这可能是一点点蛮力,但嘿......已经晚了。

d = {'Date': ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'], 'Country Code': ['93', '92', '91', '90'], 'Area Code': ['1,2,3,4,5,6,7', '31,32,43,44,54,56,7, ', '434,34,4', '00, 89']}

new = {'Date': d['Date'], 'Combined Code': []}

for i, code in enumerate(d['Country Code']):
    area = map(str.strip, d['Area Code'][i].split(','))
    new['Combined Code'].append(",".join(["".join(item) for item in zip([code] * len(area), area)]))

print new

<强>输出

{'Date': ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'], 'Combined Code': ['931,932,933,934,935,936,937', '9231,9232,9243,9244,9254,9256,927,92', '91434,9134,914', '9000,9089']}

答案 1 :(得分:1)

我想出了这个。期望输出的差异是由于输入中的空格。

d = {'Date' : ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'],
     'Country Code' : ['93', '92', '91', '90'],
     'Area Code' : ['1,2,3,4,5,6,7', '31,32,43,44,54,56,7, ', '434,34,4', '00, 89']};

merged = [];

# assumes that the length of "Country Code" is always the same as "Area Code"
for index in range(0, len(d["Area Code"])):
    merged.append(",".join(map(lambda x: d["Country Code"][index] + x.strip(), d["Area Code"][index].split(","))));

# add the result to the dictionary and remove the old entries
d["Combined Code"] = merged;
del d["Country Code"];
del d["Area Code"];

print d;