简体   繁体   English

从字典列表中提取字符串python

[英]Extract the strings from list of dictionaries python

I have below list of dictionaries. 我有以下词典列表。

self.local_devices_list =[
    {'type': '\x02', 'device_name': u'USB HID, ManufStr="", ProdStr="QWER1025", 
     SerialNum="ABCDEF0123456789", VendorID="0xa34", ProdID="0x4007"'},
    {'type': '\x02', 'device_name': u'USB HID, ManufStr="", ProdStr="ASDF452x", 
     SerialNum="ABCDEF0123456789", VendorID="0xa34", ProdID="0x4007"'}
]

I have extracted the value for key 'device_name' using the list comprehension 我已使用列表推导提取了键“ device_name”的值

device_names = [d["device_name"].encode("utf-8") for d in self.local_devices_list if "device_name" in d]

I want to extract the information of device_name into separate strings like below 我想将device_name的信息提取到单独的字符串中,如下所示

 1. ProdStr = QWER1025
 2. SerialNum = ABCDEF0123456789
 3. VendorID = 0xa34
 4. ProdID = 0x4007

A regex can solve this dict easily. 正则表达式可以轻松解决此问题。

import re
regex = re.compile(r'(\w+)="(\w*)"', flags=re.IGNORECASE)
for d in device_names:
    print(dict(regex.findall(d)))

{'ManufStr': '', 'ProdStr': 'QWER1025', 'SerialNum': 'ABCDEF0123456789', 'VendorID': '0xa34', 'ProdID': '0x4007'} {'ManufStr':'','ProdStr':'QWER1025','SerialNum':'ABCDEF0123456789','VendorID':'0xa34','ProdID':'0x4007'}

{'ManufStr': '', 'ProdStr': 'ASDF452x', 'SerialNum': 'ABCDEF0123456789', 'VendorID': '0xa34', 'ProdID': '0x4007'} {'ManufStr':'','ProdStr':'ASDF452x','SerialNum':'ABCDEF0123456789','VendorID':'0xa34','ProdID':'0x4007'}

You can use .values() and list(). 您可以使用.values()和list()。 values() will extract the values from the dictionary into a valueView, and list() will extract them to a list. values()将字典中的值提取到valueView中,而list()将其提取到列表中。 If they are of string-type everything is good, otherwise you need to convert to string as you extract them from the list. 如果它们是字符串类型,那么一切都很好,否则从列表中提取它们时,需要转换为字符串。

Eg: 例如:

ExtractedValues = list(self.local_devices_list.values())
str(ExtractedValues[0])

You can split your variable like this : 您可以像这样拆分变量:

device_names[0].split(', ')

This will give you a lit of items that you should be able to process. 这将为您提供一些您应该能够处理的项目。

['USB HID', 'ManufStr=""', 'ProdStr="QWER1025"', 'SerialNum="ABCDEF0123456789"', 'VendorID="0xa34"', 'ProdID="0x4007"']

Hope this helps. 希望这可以帮助。

You can join them: 您可以加入他们:

information = [[" ".join(t) for t in d.items()] for d in self.local_devices_list]

Just add the filters you need into the lists comprehension. 只需将所需的过滤器添加到列表推导中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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