Converting a list of strings to dictionary - python

['key=IAfpK', ' age=58', ' key=WNVdi', ' age=64', ' key=jp9zt', ' age=47', ' key=0Sr4C', ' age=68', ' key=CGEqo', ' age=76', ' key=IxKVQ', ' age=79', ' key=eD221', ' age=29']
I got the following list, i need to convert it to a dictionary,like
{"IAfpK":58,"WNVdi":,"64":,.....}
I have tried ast library and JSON.loads but in vain

Simple one-liner using a dict comprehension:
{x.split("=")[1]: int(y.split("=")[1]) for x,y in zip(arr[::2],arr[1::2])}
zip(arr[::2],arr[1::2]) iterates over pairs of the array, and str.split extracts the correct value for the key and value.

If you know that your list is always following this exact format and order, just loop through the list:
mydict = {}
for element in mylist:
if "key=" in element:
mydict[element.replace("key=", "")] = None
else:
mydict[mydict.keys()[-1]] = int(element.replace("age=", ""))

Given you a list arr of the shape [' key=aKey', ' age=valueForAKey', ' key=bKey', ...] (note the space at the start of each list element).
You can use this dictionary comprehension to extract the matching key and values and build the resulting dictionary.
{arr[i][5:]: arr[i+1][5:] for i in range(0, len(arr), 2)}
Try it out here: https://www.online-python.com/iGI3A2YEnr
If the number of leading spaces is inconsistent (as in the example you gave), you can use the lstrip() method to remove the leading spaces.
{arr[i].lstrip()[4:]: arr[i+1].lstrip()[4:] for i in range(0, len(arr), 2)}

Related

how to filter string of dictionary from a list of python?

I have a list tht contains strings, and those string could be a simple string or key value pair in a string. Please see below sample
c = ['Success, no result', 'num_parts: 55', 'num_boards: 2', 'xyz', 'adsqwrqw']
I know a way to Convert String to List of dictionaries using json.loads() + replace() method. But the condition is to have all elements as dictionary.
But in my case, a list contains a string, and dictionary as a string. How to filter in such condition?
Any suggestion
You can check for th ":" in the string as that is the key which differentiates dictionary compliant strings like this :-
lst = ['Success, no result', 'num_parts: 55', 'num_boards: 2', 'xyz', 'adsqwrqw']
DictL, StrL = [], []
for i in lst:
if ":" in i:
DictL.append(i)
else:
StrL.append(i)
You can also further compress it to a List comprehension like this :-
lst = ['Success, no result', 'num_parts: 55', 'num_boards: 2', 'xyz', 'adsqwrqw']
DictL, StrL = [i for i in lst if ":" in i], [i for i in lst if ":" not in i]
I think you can check if ': ' is in the string by a simple if command:
for string in c:
if ': ' in string:
#do something with dictionary string
else:
#do something with simple string

Iterating through an arbitrarily nested array in python and changing matching values

I have an arbitrarily nested array of values that looks like this:
['"multiply"', 'ALAssn ', ['ACmp ', ['Ge ', ['Var "n"'], ' ', ['Num 0']]], ['ALAssn ', ['ACmp ', ['Eq ', ['Var "p"'], ' ', ['Mul ', ['Var "n"'], ' ', ['Var "m"']]]]]
and I need to try and figure out a way to parse through the every value in the array and format it so that:
Each array of length 1 is split into two separate values:
-- Example: ['Var "n"'] should now become ["Var", "n"] and ['Num 0'] now becomes ["Num", 0].
All instances of empty list values are removed.
-- Example: ['Ge ', ['Var "n"'], ' ', ['Num 0']] now becomes ['Ge ', ['Var "n"'], ['Num 0']]
The whitespace in any string is removed.
-- Example: 'Ge ' now becomes 'Ge'
The given snippet is a portion of a much larger string that needs to parsed. I understand what needs to be done at a high level..ie:
Once I get to an list of length 1, list.split(" ") to split into two separate elements, then trim arr[1] to get rid of the extra quotation marks
If el is an empty string for every element in the list, list.remove(el)
Check if isinstance(el, string) of every element when traversing, and if true, el.replace(" ", "") to rid of the whitespace.
My only issue comes when traversing through every single element in the list. I've tried doing so recursively and iteratively, but so far haven't been able to crack it.
Ideally, I traverse through every single element, and then once I hit an element that meets the criteria, set that element equal to the change that I want to make on it. This is only really the case for points 1 and 3.
EDIT:
Thank you so much for the answers given. I have one more addition I would like to make.
Assume too I have a nested identifiers like 'Reads "a"' as the first value of an array, with the possibility of having addition identifiers like Write "a" in the same level. These also needs to be converted to the format ["Read", "a"]. See the change in the large list below. How would I go about doing this?
['Read "a"', ['Add', ['Var', 'i'], ['Num', '1']]], 'Write "a"', ['Add', ['Var', 'i'], ['Num', '1']], ['Var', 't']]
The point of these values 'Read' and 'Write' is so that, when traversing the list, we know the "type" of the next n elements of the list corresponding to that identifier. We can distinguish them basically by saying they are are the only values in the nested list that will not be lists themselves.
For example: ['identifier', [], [], []]
Assume it is known that the identifier type contains 3 lists, first, second, third. The goal is to read identifier and then store first, second, and third as nodes in a tree, for example.
This problem seems like it would be easiest to deal with by constructing a new list with the fixed-up items, rather than trying to modify the existing list in place. This would let you use recursion to deal with the nesting, while using iteration over the flat parts of each list.
I'd structure the code like this:
def process(lst):
if len(lst) == 1: # special case for one-element lists
result = lst[0].split()
result[1] = result[1].strip('"') # strip quotation marks
return result
result = []
for item in lst:
if isinstance(item, list):
result.append(process(item)) # recurse on nested lists
else: # item is a string
stripped = item.strip() # remove leading and trailing whitespace
if stripped:
result.append(stripped) # keep only non-empty strings
return result
Seems you can collapse 1 and 3 into one operation:
def sanitize(item):
if isinstance(item, list):
if len(item) == 1:
item = item[0].split()
return [output for i in item if (output := sanitize(i))]
return item.strip('" ') # Strips both '"' and ' '.
item = ['"multiply"', 'ALAssn ', ['ACmp ', ['Ge ', ['Var "n"'], ' ', ['Num 0']]], ['ALAssn ', ['ACmp ', ['Eq ', ['Var "p"'], ' ', ['Mul ', ['Var "n"'], ' ', ['Var "m"']]]]]]
sanitize(item)
# Returns: ['multiply', 'ALAssn', ['ACmp', ['Ge', ['Var', 'n'], ['Num', '0']]], ['ALAssn', ['ACmp', ['Eq', ['Var', 'p'], ['Mul', ['Var', 'n'], ['Var', 'm']]]]]]

python remove single quotes and spaces from a list

Im using python3 and i want to make this list to containe only the temp items and removing all the spaces and singel quotes.
a = ["', ' 'temp1', ' 'temp12', ' 'temp3', ' 'temp4', ' 'temp5' "]
I want it to look like this :
['temp1','temp12','temp3','temp4','temp5']
How can i do this ?
Things like this was explained here billion times, but here you are:
import re
pattern = r'(\w+\d+)'
s = "', ' 'temp1', ' 'temp12', ' 'temp3', ' 'temp4', ' 'temp5' "
result = re.findall(pattern, s)
Result:
['temp1', 'temp12', 'temp3', 'temp4', 'temp5']
One way to go about this :
result = a[0].replace(' ', '').replace("'", '')[1:].split(',')
print(result)
Output:
['temp1', 'temp12', 'temp3', 'temp4', 'temp5']
I tried splitting the list element over single quote and then traversed through all the elements of the created list (used list comprehension) : fetched only those elements which contain the word 'temp'
print ([i for i in a[0].split("'") if 'temp' in i])

Python : Get the values of list of keys from list of dictionaries

I have list of
List=[{'ManufStr': '',
'ProdStr': 'QWER1025',
'SerialNum': 'ABCDEF0123456789',
'VendorID': '0xa34',
'ProdID': '0x4007'},
{'ManufStr': '',
'ProdStr': 'ASDF452x',
'SerialNum': 'ABCDEF0123456789',
'VendorID': '0xa34',
'ProdID': '0x4007'}]
How can i get the values of VendorID, ProdID and ProdStr and then join them all together to make one string string?
such as VID0xa34&PID0x4007 ASDF452x
Try this:
>>> ['VID' + item['VendorID'] + '&PID' + item['ProdID'] + ' ' + item['ProdStr'] for item in List]
For the List you provided above it will output:
['VID0xa34&PID0x4007 QWER1025', 'VID0xa34&PID0x4007 ASDF452x']
Hope it helps!
You need to loop through the dictionaries in the list.
for item in List:
print "VID{}&PID{} {}".format(
item["VendorID"], item["ProdID"], item["ProdStr"])
What aboud string template and list comprehension?
infos = ( 'VID{}&PID{} {}'.format(item['VendorID'], item['ProdID'], item['ProdStr']) for item in List )
`print ['VID' + item['VendorID'] + '&PID' + item['ProdID'] + ' ' + item["ProdStr"] for item in List]`
Output: ['VID0xa34PID0x4007 QWER1025', 'VID0xa34PID0x4007 ASDF452x']
Try something​like this,
result = []
for item in List:
all_string = "VID{}&PID{}{}".format(item['VendorID'], item['ProdID'], item['ProdStr'])
result.append(all_string)

Checking if an item in a list is in another list

values = ['Limpets', 'Mussels', 'Phytoplankton', 'Zooplankton', 'Prawn', 'Crab', 'Whelk', 'Seaweed']
keys = ['Whelk ', 'Mussels ', 'Bird ', 'Prawn ', 'Fish ', 'Zooplankton ', 'Crab ', 'Lobster ', 'Limpets ']
What I want is the items in values that are not in keys. I have tried writing it as:
for item in values:
if item not in keys:
print(item)
the answer is should get is
phytoplankton
seaweed
but what i get instead is:
Phytoplankton
Seaweed
Limpets
Mussels
Crab
Whelk
Prawn
Zooplankton
I also tried storing the item in a list and then printing that list but nothing I've tried is working for me. I saw some answers using list comprehension but I'm taking an introductory course so all I've got is loops... I'm using python3.5 if that makes any difference.
Just use sets
set(values).difference(set(keys))
Or for this particular example OP can use
set(values).difference(set([i.strip() for i in keys]))
Since the keys list has a trailing space for each item so we need to clear that up.
in keys list you have spaces after words for example 'Whelk ', but in values you don't f.e 'Whelk'. 'Whelk ' and 'Whelk' are two different words so when you write
if item not in keys:
it returns true. you should remove whitespace after words in keys list first and then try your code sample
Your code is correct. The thing is, each string in your keys list contains a space at the end. This code:
values = ['Limpets', 'Mussels', 'Phytoplankton', 'Zooplankton', 'Prawn', 'Crab', 'Whelk', 'Seaweed']
keys = ['Whelk', 'Mussels', 'Bird', 'Prawn', 'Fish', 'Zooplankton', 'Crab', 'Lobster', 'Limpets']
for item in values:
if item not in keys:
print(item)
produces this output:
PhytoplanktonSeaweed
If for some reason you cannot modify the entires of keys, you can modify your loops to be:
for item in values:
if item + " " not in keys:
print(item)
which will give you the same output:
PhytoplanktonSeaweed
I think this is what you want:
[x for x in values if x not in keys]
as per you question below will help
[i for i in keys if i.strip() not in values]
Also, you can use set in python for more evaluations of this kind
It will return the whole list because your keys contains additional spaces in each string so you have to remove the spaces first.
updated_keys = [i.strip() for i in keys]
answer_list = [i for i in values if i not in updated_keys]
list(set(values) - set([i.strip() for i in keys]))
You first need to use map(lambda x : x.strip(),keys) then use reduce or any other solution
values = ['Limpets', 'Mussels', 'Phytoplankton', 'Zooplankton', 'Prawn', 'Crab', 'Whelk', 'Seaweed']
keys = ['Whelk ', 'Mussels ', 'Bird ', 'Prawn ', 'Fish ', 'Zooplankton ', 'Crab ', 'Lobster ', 'Limpets ']
map(lambda x : x.strip(),keys)
reduce(lambda x , y : x+ [y] if y.strip() not in keys else x, values,[])
O/P : ['Phytoplankton', 'Seaweed']

Categories

Resources