I'd like to convert lists of formatted strings into a dictionnary.
the strings formatted like this:
str = 'abcd="efgh"'
And i'd like to get this into a dict like this:
d = {'abcd': 'efgh'}
Example:
l = ['abc="efg"', 'hij="klm"', 'nop="qrs"']
into >
d = {'abc': 'efg', 'hij': 'klm', 'nop' :'qrs'}
I tried the following :
d = dict(element.split('=') for element in l)
-> but this doesn't work
Thanks.
You can parse the list and break each element using the split method and then add it to dict. Adding sample code:
d = {}
for element in l:
string_elements = element.split("=")
d[string_elements[0]] = string_elements[1].replace('"','')
Related
I have an integer object for example a = 1234 and I want to convert it to a list, so it would look something like [1234].
I tried converting it into a string first and then converting it to a list but that gives me [1,2,3,4].
Any suggestions?
You can just cover it in brackets.
a = 1234
print([a])
Or append()
b = []
b.append(a)
output
[1234]
Here:
a = 1234
lst = []
lst.append(a)
print(lst) #[1234]
If you are trying to convert in to string, use str()
>>> str(1234)
'1234'
If you are trying to put your int in a list, use []:
>>> var = 1234
>>> [var]
[1234]
or do:
>>> l = []
>>> l.append(var)
>>> l
[1234]
Just cover it with brackets:
a=1243
a=[a]
or create a list and append a
b = []
b.append(a) # or you could do b=[a]
I got a list of strings. Those strings have all the two markers in. I would love to extract the string between those two markers for each string in that list.
example:
markers 'XXX' and 'YYY' --> therefore i want to extract 78665786 and 6866
['XXX78665786YYYjajk', 'XXX6866YYYz6767'....]
You can just loop over your list and grab the substring. You can do something like:
import re
my_list = ['XXX78665786YYYjajk', 'XXX6866YYYz6767']
output = []
for item in my_list:
output.append(re.search('XXX(.*)YYY', item).group(1))
print(output)
Output:
['78665786', '6866']
import re
l = ['XXX78665786YYYjajk', 'XXX6866YYYz6767'....]
l = [re.search(r'XXX(.*)YYY', i).group(1) for i in l]
This should work
Another solution would be:
import re
test_string=['XXX78665786YYYjajk','XXX78665783336YYYjajk']
int_val=[int(re.search(r'\d+', x).group()) for x in test_string]
the command split() splits a String into different parts.
list1 = ['XXX78665786YYYjajk', 'XXX6866YYYz6767']
list2 = []
for i in list1:
d = i.split("XXX")
for g in d:
d = g.split("YYY")
list2.append(d)
print(list2)
it's saved into a list
I have an array of dictionaries d which I obtain by parsing a JSON file: d = r.json()
Assuming d then contains
d = [
{'change':'112','end_time':'2020-05-12','hostname':'a,b,c,d,e','ref':'345','start_time':'202-04-2020'},
{'change':'182','end_time':'2020-05-12','hostname':'a1,b1,c1,d1,e1','ref':'325','start_time':'202-04-2020'},
{'change':'122','end_time':'2020-05-12','hostname':'g,h,i,j,k','ref':'315','start_time':'202-04-2020'},
{'change':'112','end_time':'2020-05-12','hostname':'o,t1,h1,e4,n7','ref':'345','start_time':'202-04-2020'},
]
where all the hostnames are different from each other, how can I then perform a search like
if hostname=='a1':
print change (i.e 182)
You need to iterate over the list, split the hostnames into a list and check if the hostname you are searching for exists in that list.
hostname = 'a1'
for row in d:
hostnames = row['hostname'].split(',')
if hostname in hostnames:
print(row['change'])
The Pythonic way of solving this (using a comprehension) is also the easiest.
# for your a1 example
change_a1 = [i['change'] for i in d
if 'a1' in i['hostname']]
For an arbitrary search, just wrap it as a function
def find_change(host):
change = [i['change'] for i in d
if host in i['hostname']]
return change
First of all you have a lot of json structure errors:
d=[{'change':'112','end_time':'2020-05-12','hostname':'a,b,c,d,e','ref':'345','start_time':'202-04-2020'},
{'change':'182','end_time':'2020-05-12','hostname':'a1,b1,c1,d1,e1','ref':'325','start_time':'202-04-2020'},
{'change':'122','end_time':'2020-05-12','hostname':'g,h,i,j,k','ref':'315','start_time':'202-04-2020'},
{'change':'112','end_time':'2020-05-12','hostname':'o,t1,h1,e4,n7','ref':'345','start_time':'202-04-2020'}]
hostname='a1'
for row in d:
arr = row['hostname'].split(",")
if hostname in arr:
print(row['change'])
#parse all the keys for learning.
for row in d:
for k in row.keys():
if k == "hostname":
arr = row[k].split(",")
for s in arr:
#print(s)
if s =='a1':
row['change'] = '777'
print(d)
after that use reverse to re-arrange the tuples in json.
Have fun !
I am trying to make a list containing 2 strings:
List=["Hight = 7.2", "baselength = 8.32"]
But I am having a problem trying to extract the numbers from the strings:
For example:
If "Hight = 7.2" then the result should be: 7.2
or if the "Hight= 7.3232" then the result should be: 7.3232
Using re.findall :
>>> out = []
>>> for s in l:
out.append( float(re.findall('\d+(?:\.\d+)?', s)[0]) )
>>> out
=> [7.2, 8.0]
Or, without regex, using split,
>>> out = []
>>> for s in l:
num = s.replace(' ','').split('=')[1]
#note : removed whitespace so don't have to deal with cases like
# `n = 2` or `n=2`
out.append(float(num))
>>> out
=> [7.2, 8.0]
#driver values :
IN : l = ["Hight = 7.2","baselength = 8"]
How about this
[(item.split('=')[0],float(item.split('=')[1]) ) for item in List]
Output :
[('Hight ', 7.2), ('baselength ', 8.32)]
Having a label associated to a value is best managed with a dictionary, however if you must have each label=value pair as an entry in a list because perhaps you are reading it into Python from elsewhere, you could use the re module to extract the numeric value from each string in the list:
import re
list=["height = 7.2", "length = 8.32"]
for dim in list:
print(float(re.search('\d+.\d+', dim).group()))
You could convert your list to a dictionary using a comprehension:
import re
List=["Height = 7.2", "baselength = 8.32"]
rx = re.compile(r'(?P<key>\w+)\s*=\s*(?P<value>\d+(?:\.\d+)?)')
Dict = {m.group('key'): float(m.group('value'))
for item in List
for m in [rx.search(item)]}
print(Dict)
# {'Height': 7.2, 'baselength': 8.32}
Afterwards, you can access your values with e.g. Dict["Height"] (here: 7.2).
It's very simple. Use this method for any type of value
List=["Hight = 7.2", "baselength = 8.32"]
# showing example for one value , but you can loop the entire list
a = List[0].split("= ")[1] #accessing first element and split with "= "
print a
'7.2'
I have a string :
datalist = "popupWin:'http://www.adachikan.net/index.php/catalog/product/gallery/id/3049/image/1861/', useZoom: 'cloudZoom', smallImage: 'http://www.adachikan.net/media/catalog/product/cache/1/image/315x400/9df78eab33525d08d6e5fb8d27136e95/1/8/187267-875-40.jpg'"
And i want to convert this string into Python Dict. I can use split to break the string and form list:
datalist.split(',') = ["popupWin:'http://www.adachikan.net/index.php/catalog/product/gallery/id/3049/image/1861/'",
" useZoom: 'cloudZoom'",
" smallImage: 'http://www.adachikan.net/media/catalog/product/cache/1/image/315x400/9df78eab33525d08d6e5fb8d27136e95/1/8/187267-875-40.jpg'"]
And so on to get the desired result...
I there any easy way to use this datalist as a dict like : datalist['smallImage'] etc..
Split each item after splitting by ',', by ':'. like so:
datadict = {}
for item in datalist.split(','):
key, value = item.split(':', 1)
datadict[key.strip()] = value.strip()
Use a dict comprehension with str.split and str.strip:
>>> dic = {k.strip(): v.strip().strip("'")
for k,v in (x.split(':',1) for x in datalist.split(','))}
>>> dic
{'useZoom': 'cloudZoom', 'popupWin': 'http://www.adachikan.net/index.php/catalog/product/gallery/id/3049/image/1861/', 'smallImage': 'http://www.adachikan.net/media/catalog/product/cache/1/image/315x400/9df78eab33525d08d6e5fb8d27136e95/1/8/187267-875-40.jpg'}
>>> dic['smallImage']
'http://www.adachikan.net/media/catalog/product/cache/1/image/315x400/9df78eab33525d08d6e5fb8d27136e95/1/8/187267-875-40.jpg'