使字典键和值正确排列。
import pprint
old_dict = {'A B':['C D'],'E F':['G H'],'I J':['K L'],'M N':['O P'],'Q R':['S T'], 'U V':['W X']}
new_dict = {}
for x in old_dict:
try:
for i in range(0,2):
key = x.split()[i]
value = old_dict[x][0].split()[i]
new_dict[key] = value
except:
pass
pprint.pprint(new_dict)
上面的代码工作正常并返回:
{'A': 'C',
'B': 'D',
'E': 'G',
'F': 'H',
'I': 'K',
'J': 'L',
'M': 'O',
'N': 'P',
'Q': 'S',
'R': 'T',
'U': 'W',
'V': 'X'}
唯一的问题是当我将old_dict更改为以下内容时:
old_dict = {'AB':['C D'],'E F':['GH'],'IJ':['KL'],'M N':['O P'],'Q R':['S T'], 'U V':['W X']}
它返回:
{'AB': 'C',
'E': 'GH',
'IJ': 'KL',
'M': 'O',
'N': 'P',
'Q': 'S',
'R': 'T',
'U': 'W',
'V': 'X'}
我想跳过没有空格分隔的键与空格分隔值配对,并且还跳过不用空格分隔的值与空格分隔键配对(即,我想跳过' AB':'C','E':'GH', - 上面例子中的其余部分都没问题。)
我该怎么办?
答案 0 :(得分:0)
我在手机上这样做,所以我现在无法真正测试它,但是应该这样做:
d = {'A B':['C D'],'E F':['G H'],'I J':['K L'],'M N':['O P'],'Q R':['S T'], 'U V':['W X']}
answer = {}
for k in d:
k = k.split()
if len(k) == 1: continue
v = d[k][0].split()
if len(v) == 1: continue
for a,b in zip(k,v):
answer[a] = b
答案 1 :(得分:0)
经测试可以正常使用:
import pprint
old_dict = {'AB':['C D'],'E F':['GH'],'I J':['K L'],'M N':['O P'],'Q R':['S T'], 'U V':['W X']}
new_dict = {}
for x in old_dict:
try:
for i in range(0,2):
key = x.split()[i]
if len(key) == 1:
if len(old_dict[x][0].split()[i]) == 1:
value = old_dict[x][0].split()[i]
new_dict[key] = value
except:
pass
pprint.pprint(new_dict)
答案 2 :(得分:0)
import pprint
old_dict = {'AB':['C D'],'E F':['GH'],'IJ':['KL'],'M N':['O P'],'Q R':['S T'], 'U V':['W X']}
new_dict = {}
for x in old_dict:
try:
if(len(x)==len(old_dict[x][0])):
for i in range(0,2):
key = x.split()[i]
value = old_dict[x][0].split()[i]
new_dict[key] = value
except:
pass
pprint.pprint(new_dict)
答案 3 :(得分:0)
你可以使用dict理解:
T()
答案 4 :(得分:0)
试试这个:
import pprint
old_dict = {'AB':['C D'],'E F':['GH'],'I J':['K L'],'M N':['O P'],'Q R':['S T'], 'U V':['W X']}
new_dict = {}
for x in old_dict:
for i in range(0,2):
if ' ' in x:
key = x.split()[i]
else:
key = x.replace("", " ")[1:-1]
key = key.split()[i]
if ' ' in old_dict[x][0]:
value = old_dict[x][0].split()[i]
else:
value = old_dict[x][0].replace("", " ")[1:-1]
value = value.split()[i]
new_dict[key] = value
pprint.pprint(new_dict)