How to convert string to dict - python

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'

Related

Converting a list with multiple values into a dictionary

I have the following list and am wanting to convert it into a dictionary where the 4 digit value at the start of each item becomes the id.
['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
I have tried many different methods but it doesn't seem to work.
You can use str.split, map and dictionary comprehension
# data holds the list you have provided
{splitted[0]:splitted[1:] for splitted in map(lambda item:item.split(','), data)}
OUTPUT:
Out[35]:
{'3574': ['A+', '2021-03-24'],
'3575': ['O+', '2021-04-03'],
'3576': ['AB-', '2021-04-09'],
'3580': ['AB+', '2021-04-27'],
'3589': ['A+', '2021-05-08'],
'3590': ['B-', '2021-05-11']}
You can use dictionary comprehension with str.split:
lst = [
"3574,A+,2021-03-24",
"3575,O+,2021-04-03",
"3576,AB-,2021-04-09",
"3580,AB+,2021-04-27",
"3589,A+,2021-05-08",
"3590,B-,2021-05-11",
]
out = {int(v.split(",")[0]): v.split(",")[1:] for v in lst}
print(out)
Prints:
{
3574: ["A+", "2021-03-24"],
3575: ["O+", "2021-04-03"],
3576: ["AB-", "2021-04-09"],
3580: ["AB+", "2021-04-27"],
3589: ["A+", "2021-05-08"],
3590: ["B-", "2021-05-11"],
}
Here is the code to do what I believe you asked for. I have also added comments in the code for a bit more clarification.
my_list = ['3574,A+,2021-03-24',
'3575,O+,2021-04-03',
'3576,AB-,2021-04-09',
'3580,AB+,2021-04-27',
'3589,A+,2021-05-08',
'3590,B-,2021-05-11']#your list
my_dict = {}#The dictionary you want to put the list into
print("Your list:", my_list, "\n")
for item in my_list:#cycles through every item in your list
ID, value = item.split(",", 1)#Splits the item in your list only once (when it sees the first comma)
print(ID + ": " + value)
my_dict[ID] = value#Add the ID and value to your dictionary
print("\n" + "Your desired dictionary:", my_dict)
Which outputs this:
Your list: ['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
3574: A+,2021-03-24
3575: O+,2021-04-03
3576: AB-,2021-04-09
3580: AB+,2021-04-27
3589: A+,2021-05-08
3590: B-,2021-05-11
Your desired dictionary: {'3574': 'A+,2021-03-24', '3575': 'O+,2021-04-03', '3576': 'AB-,2021-04-09', '3580': 'AB+,2021-04-27', '3589': 'A+,2021-05-08', '3590': 'B-,2021-05-11'}
Enjoy!
TRY:
result = dict(i.split(',', 1) for i in lst)
OUTPUT:
{'3574': 'A+,2021-03-24',
'3575': 'O+,2021-04-03',
'3576': 'AB-,2021-04-09',
'3580': 'AB+,2021-04-27',
'3589': 'A+,2021-05-08',
'3590': 'B-,2021-05-11'}

How to convert a list to a dict?

I am using subprocess to print the output of ls.
output = subprocess.getoutput("ssh -i key.pem ubuntu#10.127.6.83 ls -l --time-style=long-iso /opt/databases | awk -F' ' '{print $6 $8}'")
lines = output.splitlines()
print(lines)
format = '%Y-%m-%d'
for line in lines:
if line != '':
date = datetime.strptime(line, format)
And when I print lines am getting a large list in the following format:
['', '2019-04-25friendship_graph_43458', '2019-07-18friendship_graph_45359', '2019-09-03friendship_graph_46553', '2019-10-02friendship_graph_46878']
I am trying to convert the above output to a dict with the dates in '%Y-%m-%d' format. So output would be something like:
{ '2019-04-25' : 'friendship_graph_43458',
'2019-07-18': 'friendship_graph_45359',
'2019-09-03': 'friendship_graph_46553' }
and so on, but not quite sure how to do so.
Technically if you don't want to use re if all dates are formatted the same then they will all be 10 characters long thus just slice the strings to make the dict in a comprehension:
data = ['', '2019-04-25friendship_graph_43458', '2019-07-18friendship_graph_45359', '2019-09-03friendship_graph_46553', '2019-10-02friendship_graph_46878']
output = {s[:10]: s[10:] for s in data if len(s) > 10}
{'2019-04-25': 'friendship_graph_43458', '2019-07-18': 'friendship_graph_45359', '2019-09-03': 'friendship_graph_46553', '2019-10-02': 'friendship_graph_46878'}
You could use a regular expression for each item in the list. For example:
(\d{4}-\d{2}-\d{2})(.*)
Then, you can just iterate through each item in the list and use the regular expression to the get the string in its two parts.
>>> import re
>>> regex = re.compile(r"(\d{4}-\d{2}-\d{2})(.*)")
>>> items = ['', '2019-04-25friendship_graph_43458', '2019-07-18friendship_graph_45359', '2019-09-03friendship_graph_46553', '2019-10-02friendship_graph_46878']
>>> items_dict = {}
>>> for i in items:
match = regex.search(i)
if match is None:
continue
items_dict[match.group(1)] = match.group(2)
>>> items_dict
{'2019-04-25': 'friendship_graph_43458', '2019-07-18': 'friendship_graph_45359', '2019-09-03': 'friendship_graph_46553', '2019-10-02': 'friendship_graph_46878'}
For lines that start with the date; use slices to separate the key from the value.
>>> s = '2019-04-25friendship_graph_43458'
>>> d = {}
>>> d[s[:10]] = s[10:]
>>> d
{'2019-04-25': 'friendship_graph_43458'}
>>>
Use re.findall and dictionary comprehension:
import re
lst = ['', '2019-04-25friendship_graph_43458', '2019-07-18friendship_graph_45359', '2019-09-03friendship_graph_46553', '2019-10-02friendship_graph_46878']
dct = {k: v for s in lst for k, v in re.findall(r'(\d\d\d\d-\d\d-\d\d)(.*)', s) }
print(dct)
# {'2019-04-25': 'friendship_graph_43458', '2019-07-18': 'friendship_graph_45359', '2019-09-03': 'friendship_graph_46553', '2019-10-02': 'friendship_graph_46878'}

Python Convert a part of a String into Float

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'

convert strings like 'abcd="efgh"' to a dicts like {'abcd': 'efgh'}

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('"','')

Make List to String Python

I want to make list data to string.
My list data like this :
[['data1'],['data2'],['data3']]
I want to convert to string like this :
"[data1] [data2] [data3]"
I try to use join like this :
data=[['data1'],['data2'],['data3']]
list=" ".join(data)
But get error like this :
string= " ".join(data)
TypeError: sequence item 0: expected string, list found
Can somebody help me?
Depending on how closely you want the output to conform to your sample, you have a few options, show here in ascending order of complexity:
>>> data=[['data1'],['data2'],['data3']]
>>> str(data)
"[['data1'], ['data2'], ['data3']]"
>>> ' '.join(map(str, data))
"['data1'] ['data2'] ['data3']"
>>> ' '.join(map(str, data)).replace("'", '')
'[data1] [data2] [data3]'
Keep in mind that, if your given sample of data doesn't match your actual data, these methods may or may not produce the desired results.
Have you tried?
data=[['data1'],['data2'],['data3']]
t = map(lambda x : str(x), data)
print(" ".join(t))
Live demo - https://repl.it/BOaS
In Python 3.x , the elements of the iterable for str.join() has to be a string .
The error you are getting - TypeError: sequence item 0: expected string, list found - is because the elements of the list you pass to str.join() is list (as data is a list of lists).
If you only have a single element per sublist, you can simply do -
" ".join(['[{}]'.format(x[0]) for x in data])
Demo -
>>> data=[['data1'],['data2'],['data3']]
>>> " ".join(['[{}]'.format(x[0]) for x in data])
'[data1] [data2] [data3]'
If the sublists can have multiple elements and in your output you want those multiple elements separated by a , . You can use a list comprehension inside str.join() to create a list of strings as you want. Example -
" ".join(['[{}]'.format(','.join(x)) for x in data])
For some other delimiter other than ',' , use that in - '<delimiter>'.join(x) .
Demo -
>>> data=[['data1'],['data2'],['data3']]
>>> " ".join(['[{}]'.format(','.join(x)) for x in data])
'[data1] [data2] [data3]'
For multiple elements in sublist -
>>> data=[['data1','data1.1'],['data2'],['data3','data3.1']]
>>> " ".join(['[{}]'.format(','.join(x)) for x in data])
'[data1,data1.1] [data2] [data3,data3.1]'
>>> import re
>>> l = [['data1'], ['data2'], ['data3']]
>>> s = ""
>>> for i in l:
s+= re.sub(r"\'", "", str(i))
>>> s
'[data1][data2][data3]'
How about this?
data = [['data1'], ['data2'], ['data3']]
result = " ".join('[' + a[0] + ']' for a in data)
print(result)
How about this:
In [13]: a = [['data1'],['data2'],['data3']]
In [14]: import json
In [15]: temp = " ".join([json.dumps(x) for x in a]).replace("\"", "")
In [16]: temp
Out[16]: '[data1] [data2] [data3]'
Try the following. This can also be achieved by "Reduce":
from functools import reduce
data = [['data1'], ['data2'], ['data3']]
print(list(reduce(lambda x,y : x+y, data)))
output: ['data1', 'data2', 'data3']

Categories

Resources