我正在尝试通过从3个单独的词典中提取值的过程在python中创建主词典。 3个词典看起来像这样:
X = {'0':[1, 3, 4, 5], '.001':[2, 4, 6, 7]}
Y = {'0':[5, 6, 9, 2], '.001':[2, 6, 8, 4]}
Z = {'0':[3, 6, 8, 9], '.001':[3, 1, 5, 8]}
我希望能够将这些词典组合成一个主词典,该词典将X,Y和Z中的第一个值分组,X,Y和Z中的第二个值,依此类推。最后的字典会显示像这样的东西:
Final = {'0':[1, 5, 3], [3, 6, 6], [4, 9, 8], [5, 2, 9], '.001':[2, 2, 3].....
等等。我相信我需要使用for循环,但我不确定。任何帮助是极大的赞赏。
这是我到目前为止的代码。所有单个词典都可以正确创建,但最后一个词典没有。
Xcoord = {}
time = []
with open ('Nodal_QuardnetsX2.csv', 'r') as f:
f.readline() # Skips first line
for line in f:
values = [s.strip()for s in line.split(',')]
Xcoord[values[0]] = map(float, values[1:])
time.append(values[0])
print time
Ycoord = {}
with open ('Nodal_QuardnetsY2.csv', 'r') as f:
f.readline() # Skips first line
for line in f:
values = [s.strip()for s in line.split(',')]
Ycoord[values[0]] = map(float, values[1:])
Zcoord = {}
with open ('Nodal_QuardnetsZ2.csv', 'r') as f:
f.readline() # Skips first line
for line in f:
values = [s.strip()for s in line.split(',')]
Zcoord[values[0]] = map(float, values[1:])
counter = 0
k = len(Xcoord)
for time in range(k):
CoordCombo[time] = Xcoord[counter], Ycoord[counter], Zcoord[counter]
counter = counter + 1
答案 0 :(得分:1)
@JackRandall,他们的Final字典的语法不正确。我建议你阅读https://docs.python.org/2/tutorial/datastructures.html#dictionaries以了解字典。你可能希望你的最终字典看起来像这样:
Final = {'0':[[1, 5, 3], [3, 6, 6], [4, 9, 8], [5, 2, 9]], '.001':[[2, 2, 3].....]}
要开始使用,您可以在X中循环键,然后使用Y和Z的键访问元素,并将它们全部附加到Final [' key']的数组中。这应该让你开始,我可以回答更多的问题。
以下是基于您的评论的更新: 如果密钥在X中不存在,则将插入无
X = {'0':[1, 3, 4, 5], '.001':[2, 4, 6, 7], 'XonlyKey':[1,1,1,1,]}
Y = {'0':[5, 6, 9, 2], '.001':[2, 6, 8, 4]}
Z = {'0':[3, 6, 8, 9], '.001':[3, 1, 5, 8]}
Final={}
for key, value in X.iteritems():
tempArray=[value]
for tempDict in (Y,Z):
if key in tempDict:
tempArray.append(tempDict[key])
else:
tempArray.append(None)
Final[key]=tempArray
答案 1 :(得分:1)
以下是创建“主词典”的两个函数,它只包含所有输入词典共有的值。您提供的X,Y,Z示例没有任何三个词典共有的值,因此您最终得到一个空字典。
X = {'0':[1, 3, 4, 5], '.001':[2, 4, 6, 7]}
Y = {'0':[5, 6, 9, 2], '.001':[2, 6, 8, 4]}
Z = {'0':[3, 6, 8, 9], '.001':[3, 1, 5, 8]}
dictionaries = [X,Y,Z]
def compare(d1, d2):
d3 = {}
for key in d1:
for v in d1[key]:
if v in d2[key]:
if key in d3:
d3[key].append(v)
else: d3[key] = [v,]
return d3
def createMaster(dictionaries):
length = len(dictionaries)
if length == 1:
return dictionaries[0]
d1 = dictionaries.pop()
d2 = dictionaries.pop()
d3 = compare(d1, d2)
if length == 2:
return = d3
else:
dictionaries.append(d3)
return createMaster(dictionaries)
答案 2 :(得分:0)
是的,因为@ user3885927注意到你的语法错误。
结果作为元组列表的dict,你可以这样做:
>>> {key: zip(X[key], Y[key], Z[key]) for key in X.keys()}
{'0': [(1, 5, 3), (3, 6, 6), (4, 9, 8), (5, 2, 9)], '.001': [(2, 2, 3), (4, 6, 1), (6, 8, 5), (7, 4, 8)]}
或者作为列表元组的词典:
>>> {key: tuple([[x, y, z] for x, y, z in zip(X[key], Y[key], Z[key])]) for key in X.keys()}
{'0': ([1, 5, 3], [3, 6, 6], [4, 9, 8], [5, 2, 9]), '.001': ([2, 2, 3], [4, 6, 1], [6, 8, 5], [7, 4, 8])}