繁体   English   中英

如何使用python扁平化和合并字典中的值?

[英]How to flat and merge values in a dictionary using python?

我有一本这样的字典:

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()))))

但是无法在字典中管理所有这些。

这可能有点蛮力 ,但嘿……已经晚了。

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']}

我只是想出了这个。 所需输出的差异是由于输入中的空格所致。

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM