简体   繁体   English

如何用字典作为值反转列表中的键值对?

[英]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))
  1. Iterate on every item from the given tuple. 迭代给定元组中的每个项目。
  2. Iterate second element for the item ie dictionary part. 迭代项目的第二个元素,即字典部分。
  3. create new item ie (({key:value},), item[0]) 创建新项目,即(({{key:value},),item [0])
  4. Append result into output variable. 将结果附加到输出变量中。

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.

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