[英]How to reverse key value pair in list with dictionary as value?
I have a key value pair as below: 我有一个键值对,如下所示:
((1,{'foo':1,'abc':2,'xyz':3,'def':2}),(2,{'ghu':3,'kie':2}))
I was able to reverse the key value pair to below form: 我能够将键值对反转为以下形式:
((({'foo':1,'abc':2,'xyz':3,'def':2}),1),(({'ghu':3,'kie':2})),2)
But I need the in them in the following format.Tried with various options but was not successful 但是我需要以以下格式输入它们。尝试了各种选项但未成功
(({'foo':1}),1)
(({'abc':2}),1)
(({'xyz':3}),1)
(({'def':2}),1)
(({'ghu':3}),2)
(({'kie':2}}),2)
Could any one help me with this? 有人可以帮我吗?
This list comprehension will produce your desired format: 此列表理解将产生您所需的格式:
l = ((1,{'foo':1,'abc':2,'xyz':3,'def':2}),(2,{'ghu':3,'kie':2}))
tuple((({k:v}),i) for i,j in l for k,v in j.items())
If tuple is what you want, then you can use a simple generator expression
like the following and then pass it to tuple()
function to get the required tuple. 如果需要元组,则可以使用如下所示的简单generator expression
,然后将其传递给tuple()
函数以获取所需的元组。
Example - 范例-
>>> t = ((1,{'foo':1,'abc':2,'xyz':3,'def':2}),(2,{'ghu':3,'kie':2}))
>>>
>>> nt = tuple((({k:d[k]}),i) for i, d in t for k in d.keys())
>>> nt
(({'def': 2}, 1), ({'xyz': 3}, 1), ({'abc': 2}, 1), ({'foo': 1}, 1), ({'kie': 2}, 2), ({'ghu': 3}, 2))
Code: 码:
input_val = ((1,{'foo':1,'abc':2,'xyz':3,'def':2}),(2,{'ghu':3,'kie':2}))
output_val = []
for i in input_val:
for key, value in i[1].items():
output_val.append( (({key:value},), i[0]))
import pprint
pprint.pprint(output_val)
Output: 输出:
[(({'xyz': 3},), 1),
(({'foo': 1},), 1),
(({'abc': 2},), 1),
(({'def': 2},), 1),
(({'ghu': 3},), 2),
(({'kie': 2},), 2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.