如何从包含字典对象的列表中删除文本?

时间:2018-02-08 17:09:49

标签: python python-3.x

我有一个清单

CREATE TABLE [dbo].[users](
[userid] [int] IDENTITY(1,1) NOT NULL,
[realname] [nvarchar](250) NOT NULL,
[password] [varchar](250) NOT NULL,
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED 
(
[userid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

我想将其转换为

x = [{'key': 'ACT', 'value': 'Active'}, 
     {'key': 'EXP', 'value': 'Expired'}, 
     {'key': 'RCAL', 'value': 'Recall'}]

如何通过列表x ??

删除[{'ACT': 'Active', 'EXP': 'Expired', 'RCAL': 'Recall'}] 'key':

2 个答案:

答案 0 :(得分:1)

试试这个:

>>> y = {a['key']: a['value'] for a in x}
>>> y
{'ACT': 'Active', 'EXP': 'Expired', 'RCAL': 'Recall'}

阅读:Dict Comprehensions in python.

答案 1 :(得分:0)

如果您要从列表x中的每个元素创建字典,我会列出理解:

x = [{'key': 'ACT', 'value': 'Active'}, 
     {'key': 'EXP', 'value': 'Expired'}, 
     {'key': 'RCAL', 'value': 'Recall'}]

x  = [{e['key']:e['value']} for e in x]

print(x)

这导致:

[{'ACT': 'Active'}, {'EXP': 'Expired'}, {'RCAL': 'Recall'}]