Python: How to spilt string in dictionary - python

I have the following JSON Data:
json_data = {"window_string": "X=-10 H=30 Y=20 W=40"}
How would I split the values to a list that is similar to this:
window_string = ["X = -10", "Y = 20", "W=40"]

json_data = {"window_string": "X=-10 H=30 Y=20 W=40"}
print(json_data["window_string"].split()) #Use str.split()
Output:
['X=-10', 'H=30', 'Y=20', 'W=40']

split() function takes a string and splits it in list of strings, where every item in that splitted list is a word in the original string. Since json_data['window_string'] has 4 words that every word is one item in the output list, it works just fine:
json_data = {'window_string': 'X=-10 H=30 Y=20 W=40'}
window_string = json_data['window_string'].split()

Related

Convert List to A String

I am having problems keeping the data into a string format. The data converts to a list once I perform a split on each row (x.split). What do I need to do to keep the data in a string format?
from pyspark import SparkContext
sc = SparkContext.getOrCreate()
document = sc.textFile("/content/sample_data/dr_csv")
print type(document)
print document.count()
document.take(5)
document.takeSample(True, 5, 3)
record = document.map(lambda x: x.split(','))
record.take(3)
You can just have a copy of x to split it without affecting x as follows:
temp = x
record = document.map(lambda temp: temp.split(','))
You can use the .join method if you want to get a string with all of the elements of the list. Suppose you have lst = ['cat', 'dog', 'pet']. Performing " ".join(lst) would return a string with all the elements of lst separated by a space: "cat dog pet".
''.join([str(i) for i in document.map(lambda x: x.split(',')])

Extract numeric values from a string for python

I have a string with contains numeric values which are inside quotes. I need to remove numeric values from these and also the [ and ]
sample string: texts = ['13007807', '13007779']
texts = ['13007807', '13007779']
texts.replace("'", "")
texts..strip("'")
print texts
# this will return ['13007807', '13007779']
So what i need to extract from string is:
13007807
13007779
If your texts variable is a string as I understood from your reply, then you can use Regular expressions:
import re
text = "['13007807', '13007779']"
regex=r"\['(\d+)', '(\d+)'\]"
values=re.search(regex, text)
if values:
value1=int(values.group(1))
value2=int(values.group(2))
output:
value1=13007807
value2=13007779
You can use * unpack operator:
texts = ['13007807', '13007779']
print (*texts)
output:
13007807 13007779
if you have :
data = "['13007807', '13007779']"
print (*eval(data))
output:
13007807 13007779
The easiest way is to use map and wrap around in list
list(map(int,texts))
Output
[13007807, 13007779]
If your input data is of format data = "['13007807', '13007779']" then
import re
data = "['13007807', '13007779']"
list(map(int, re.findall('(\d+)',data)))
or
list(map(int, eval(data)))

Python Joining List and adding and removing characters

I have a list i need to .join as string and append characters
my_list = ['3.3.3.3', '2.2.2.3', '2.2.2.2']
my_list.append(')"')
my_list.insert(0,'"(')
hostman = '|'.join('{0}'.format(w) for w in my_list)
#my_list.pop()
print(hostman)
print(my_list)
My output = "(|3.3.3.3|2.2.2.3|2.2.2.2|)"
I need the output to be = "(3.3.3.3|2.2.2.3|2.2.2.2)"
how can i strip the first and last | from the string
You are making it harder than it needs to be. You can just use join() directly with the list:
my_list = ['3.3.3.3', '2.2.2.3', '2.2.2.2']
s = '"(' + '|'.join(my_list) + ')"'
# s is "(3.3.3.3|2.2.2.3|2.2.2.2)"
# with quotes as part of the string
or if you prefer format:
s = '"({})"'.format('|'.join(my_list))
Try this :
hostman = "("+"|".join(my_list)+")"
OUTPUT :
'(3.3.3.3|2.2.2.3|2.2.2.2)'

Convert JSON values into a string

r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'
data = json.loads(r)
for element in data:
for value in data['available_sizes']:
print(value['name'])
At the moment this prints out the following:
40
41
42
43
45
How would I then use this data as a string? Below is the desired output.
Available sizes are 40, 41, 41, 43, 45
Your outermost loop is superfluous, since you only have a single key to iterate over.
Iterate over data, append your numbers to a list, and then call str.join at the end to efficiently join your strings together.
nums = []
for v in data['available_sizes']:
nums.append(str(v['name'])) # v['name'] if it is already string
print(f'Available sizes are {', '.join(nums)}')
You can rewrite the loop using a list comprehension -
num_str = ', '.join([v['name'] for v in data['available_sizes']])
print(f'Available sizes are {num_str}')
For a primer on JSON data traversals, I recommend looking at this answer.
Use a for-comprehension to extract the size names, and then str.join() to add the comma separator:
import json
r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'
data = json.loads(r)
# Extract the size names from the list of available sizes
size_names = [size_entry["name"] for size_entry in data["available_sizes"]]
# Join the sizes names as strings using a comma separator and print
sizes_string = ", ".join(size_names)
print("Available sizes are: " + sizes_string)
Do something like that this is the out put that you want
import json
r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'
data = json.loads(r)
var = []
for element in data:
for value in data['available_sizes']:
var.append(value['name'])
print( 'Availble size are %s' %(', '.join(var)))

Python adding to the list

I have to strip whitespace for extracted strings, one string at a time for which I'm using split(). The split() function returns list after removing white spaces. I want to store this in my own dynamic list since I have to aggregate all of the strings.
The snippet of my code:
while rec_id = "ffff"
output = procs.run_cmd("get sensor info", command)
sdr_li = []
if output:
byte_str = output[0]
str_1 = byte_str.split(' ')
for byte in str_1:
sdr_li.append(byte)
rec_id = get_rec_id()
Output = ['23 0a 06 01 52 2D 12']
str_1 = ['23','0a','06','01','52','2D','12']
This does not look very elegant, transferring from one list to another. Is there another way to achieve this.
list.extend():
sdr_li.extend(str_1)
str.split() returns you a list so just add your list's items to the main list. Use extend https://docs.python.org/2/tutorial/datastructures.html
so rewriting your data into something legible and properly indented you'd get:
my_list = list
while rec_id = "ffff"
output = procs.run_cmd("get sensor info", command)
if output:
result_string = output[0]
# extend my_list with the list resulting from the whitespace
# seperated tokens of the output
my_list.extend( result_string.split() )
pass # end if
rec_id = get_rec_id()
...
pass # end while

Categories