Reputation: 49
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_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
1. ProdStr = QWER1025
2. SerialNum = ABCDEF0123456789
3. VendorID = 0xa34
4. ProdID = 0x4007
Upvotes: 0
Views: 1948
Reputation: 88
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.
Upvotes: 0
Reputation: 7058
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': 'ASDF452x', 'SerialNum': 'ABCDEF0123456789', 'VendorID': '0xa34', 'ProdID': '0x4007'}
Upvotes: 2
Reputation: 533
You can use .values() and list(). values() will extract the values from the dictionary into a valueView, and list() will extract them to a list. If they are of string-type everything is good, otherwise you need to convert to string as you extract them from the list.
E.g:
ExtractedValues = list(self.local_devices_list.values())
str(ExtractedValues[0])
Upvotes: 0
Reputation: 42718
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.
Upvotes: -1