I have result returned as from ZrangebyScore function as [b'101']. I would like to extract only 101 value and discard other additional characters. It is in byte form. How to convert it in Integer format using Python.
If you are using Py3 try this:
mylist = [b'101']
val = int(mylist[0].decode())
Related
I currently have a python dictionary where the keys are strings representing URLs, and the values are also string URLs.
#socketio.on('blacklist', namespace='/update')
def add_to_blacklist(message):
stored_blacklist.clear()
for key, val in message.items():
stored_blacklist[key] = val
lookup = {'name':'blacklist'}
resp = patch_internal('blacklist', payload={"sites":stored_blacklist}, **lookup)
However there is an issue with how python is interpreting the insertions. For example:
stored_blacklist["example.com"] = "thankspython.edu"
My desired behavior is that stored_blacklist maps "example.com" to "thankspython.edu" like so:
{'example.com':'thankspython.edu'}
However, printing stored_blacklist gives me this instead:
{'example': {'com': 'thankspython.edu'}}
How could I get the desired behavior where a string with a period character in it could be read as a normal string instead of automatically creating some pseudo-JSON object?
I have data that look like this:
data = 'somekey:value4thekey&second-key:valu3-can.be?anything&third_k3y:it%can have spaces;too'
In a nice human-readable way it would look like this:
somekey : value4thekey
second-key : valu3-can.be?anything
third_k3y : it%can have spaces;too
How should I parse the data so when I do data['somekey'] I would get >>> value4thekey?
Note: The & is connecting all of the different items
How am I currently tackling with it
Currently, I use this ugly solution:
all = data.split('&')
for i in all:
if i.startswith('somekey'):
print i
This solution is very bad due to multiple obvious limitations. It would be much better if I can somehow parse it into a python tree object.
I'd split the string by & to get a list of key-value strings, and then split each such string by : to get key-value pairs. Using dict and list comprehensions actually makes this quite elegant:
result = {k:v for k, v in (part.split(':') for part in data.split('&'))}
You can parse your data directly to a dictionary - split on the item separator & then split again on the key,value separator ::
table = {
key: value for key, value in
(item.split(':') for item in data.split('&'))
}
This allows you direct access to elements, e.g. as table['somekey'].
If you don't have objects within a value, you can parse it to a dictionary
structure = {}
for ele in data.split('&'):
ele_split = ele.split(':')
structure[ele_split[0]] = ele_split[1]
You can now use structure to get the values:
print structure["somekey"]
#returns "value4thekey"
Since the keys have a common format of being in the form of "key":"value".
You can use it as a parameter to split on.
for i in x.split("&"):
print(i.split(":"))
This would generate an array of even items where every even index is the key and odd index being the value. Iterate through the array and load it into a dictionary. You should be good!
I'd format data to YAML and parse the YAML
import re
import yaml
data = 'somekey:value4thekey&second-key:valu3-can.be?anything&third_k3y:it%can have spaces;too'
yaml_data = re.sub('[:]', ': ', re.sub('[&]', '\n', data ))
y = yaml.load(yaml_data)
for k in y:
print "%s : %s" % (k,y[k])
Here's the output:
third_k3y : it%can have spaces;too
somekey : value4thekey
second-key : valu3-can.be?anything
What I want to achieve
value = 'a.b.c.d.e'
new_value = value.split('.')
new_value[-1] = F
''.join(new_value)
Now I would like to achieve this in one line. something like below
''.join(value[-1] = F in value.split('.'))
my above expression throws error because it is kind of wrong so is there a possible way to achieve this
Value should be "1.2.3.4.5" and join doesn't work for int. You should use new_value[-1]='10' instead.
''.join(value.split('.')[:-1]+['10'])
I am currently in the process of using python to transmit a python dictionary from one raspberry pi to another over a 433Mhz link, using virtual wire (vw.py) to send data.
The issue with vw.py is that data being sent is in string format.
I am successfully receiving the data on PI_no2, and now I am trying to reformat the data so it can be placed back in a dictionary.
I have created a small snippet to test with, and created a temporary string in the same format it is received as from vw.py
So far I have successfully split the string at the colon, and I am now trying to get rid of the double quotes, without much success.
my_status = {}
#temp is in the format the data is recieved
temp = "'mycode':['1','2','firstname','Lastname']"
key,value = temp.split(':')
print key
print value
key = key.replace("'",'')
value = value.replace("'",'')
my_status.update({key:value})
print my_status
Gives the result
'mycode'
['1','2','firstname','Lastname']
{'mycode': '[1,2,firstname,Lastname]'}
I require the value to be in the format
['1','2','firstname','Lastname']
but the strip gets rid of all the single speech marks.
You can use ast.literal_eval
import ast
temp = "'mycode':['1','2','firstname','Lastname']"
key,value = map(ast.literal_eval, temp.split(':'))
status = {key: value}
Will output
{'mycode': ['1', '2', 'firstname', 'Lastname']}
This shouldn't be hard to solve. What you need to do is strip away the [ ] in your list string, then split by ,. Once you've done this, iterate over the elements are add them to a list. Your code should look like this:
string = "[1,2,firstname,lastname]"
string = string.strip("[")
string = string.strip("]")
values = string.split(",")
final_list = []
for val in values:
final_list.append(val)
print final_list
This will return:
> ['1','2','firstname','lastname']
Then take this list and insert it into your dictionary:
d = {}
d['mycode'] = final_list
The advantage of this method is that you can handle each value independently. If you need to convert 1 and 2 to int then you'll be able to do that while leaving the other two as str.
Alternatively to cricket_007's suggestion of using a syntax tree parser - you're format is very similar to the standard yaml format. This is a pretty lightweight and intutive framework so I'll suggest it
a = "'mycode':['1','2','firstname','Lastname']"
print yaml.load(a.replace(":",": "))
# prints the dictionary {'mycode': ['1', '2', 'firstname', 'Lastname']}
The only thing that's different between your format and yaml is the colon needs a space
It also will distinguish between primitive data types for you, if that's important. Drop the quotes around 1 and 2 and it determines that they're numerical.
Tadhg McDonald-Jensen suggested pickling in the comments. This will allow you to store more complicated objects, though you may lose the human-readable format you've been experimenting with
if I have a string s='ABCDEFJHI', and I slice it like this ['ABC','DEF','JHI'].
I have function encode(some calculation) which convert the sliced string into numbers.
for example 'encode('ABC' ) gives 50 , encode('DEF') gives 33, encode('JHI') gives 10
['ABC','DEF','JHI'] gives [50,33,10].
I want to do the reverse case, decode(50) gives 'ABC'
I have idea that when I encode sub-string , I create a library then I append sub-string with its number like: ('ABC':50)(do the same for all the sub-strings), later in decode I will just extract the sub-string according to the number.
How can I do this in python?
If it's reversible, I suggest to store it in reverse format (50: 'ABC'). And also, imagine a situation where the given code has not encoded before.
encode_history = {}
def encode(str):
"""some calculations which lead to the code"""
... your calculations ...
encode_history[code] = str
return code
def decode(code):
"""function to convert a code to string"""
if code in encode_history:
return encode_history[code]
else:
return None
In your encode function:
def encode(the_string):
#do whatever encoding you're doing
return (the_number,the_string)
and wherever you're using it, do:
d = dict()
for value in ["ABC","DEF","JHI"]:
encoded,decoded = encode(value)
d[encoded] = decoded
Define a function also like:
def decode(lookup_table,value):
return lookup_table[value]
and use it like:
encoded_values = list()
for value in ["ABC","DEF","JHI"]:
encoded,decoded = encode(value)
d[encoded] = decoded
encoded_values.append(encoded)
for value in encoded_values:
print("{} | {}".format(value,decode(d,value)))
[OUT]
50 | ABC
33 | DEF
10 | JHI
That said -- why are you doing this, how are you doing this, and why aren't you using some sort of real encryption for it? If it's not two-way encryption, you should almost certainly NOT be storing the data anywhere, and if it IS two-way encryption, why not just decrypt it using the opposite algorithm you used to encrypt? Just keep that in mind.....