How to convert back with dictionary keys back to original data in Python? - python-3.x

So i came across issue with converting with dictionaries. Let me show you example, perhaps it will explain it self better:
string = '/?##*'
my_dict = {'/': 'backslash', '?': 'Qmark', '#': 'numb','#': 'AT', '*': 'STAR'}
for item in string:
if item in my_dict.keys():
string = string.replace(item, my_dict[item])
print(string)
returns - backslashQmarknumbATSTAR
So as you can I was able to convert original string to given DICT values. Now how can I reverse this, what I mean is how can I convert from "backslashQmarknumbATSTAR" back to original "/?##*"

Related

string appears as subset of character in list element python

So far, I have:
my_list = ['hello', 'oi']
comparison_list = ['this hellotext', 'this oitext']
for w in my_list:
if w in comparison_list: print('yes')
However, nothing prints because no element in my_list equals any element in comparison_list.
So how do I make this check as a subset or total occurance?
Ideal output:
yes
yes
You are checking the occurrence of the complete string in the list currently. Instead you can check for the occurrence of the string inside each comparison string and make a decision. A simple approach will be to re-write the loop as below
for w in my_list:
# Check for every comparison string. any() considers atleast 1 true value
if any([True for word in comparison_list if w in word]):
print('yes')
It's because you're comparing w to the list elements. If you wanna find w in each string in your comparison_list you can use any:
my_list = ['hello', 'oi', 'abcde']
comparison_list = ['this hellotext', 'this oitext']
for w in my_list:
if any(w in s for s in comparison_list):
print('yes')
else:
print('no')
I added a string to your list and handle the 'no' case in order to get an output for each element
Output:
yes
yes
no
Edited Solution:
Apologies for older solution, I was confused somehow.
Using re module , we can use re.search to determine if the string is present in the list of items. To do this we can create an expression using str.join to concatenate all the strings using |. Once the expression is created we can iterate through the list of comparison to be done. Note | means 'Or', so any of the searched strings if present should return bool value of True. Note I am assuming there are no special characters present in the my_list.
import re
reg = '|'.join(my_list)
for item in comparison_list:
print(bool(re.search(reg, item)))

How to convert a list of strings to a bytearray?

How would I convert a list of strings to a bytearray, then get the a certain value that is part of the list back into a string?
Here is my code:
test_list = ['Hello', 'World']
a = '|'.join(test_list)
test_array = bytearray(a.encode('utf-8'))
print(test_array)
# test("Hello")
print("Count of bytes:", len(byte_array))
# How would I get "Hello" back into a string?

Convert numbers string in list to number int

In Python, I want to convert all strings in a list to integers.
So if I have:
list1 = ['10,20,30']
How do I make it:
list1 = [10,20,30]
try this:
list1 = [int(i) for i in list1[0].split(',')]
First of all you have to define what the array contains, for how you have wrote the questions the array is:
0: 10,20,30
if your array is made of strings like that then you should make a regex to identify the numbers in every string and then convert the number into an integer.
But I think that your array is actually:
0: 10
1: 20
2: 30
In this case you would want to do:
for every number in the array
make the number an integer
which would be
for num in list:
# if the value is a string
if type(num) == str: # just to be sure
num = int(num)
In python every data type is easily changeable through int, float or str, but remember to assign the number after you have converted it.
int(num) would make a number an integer but would not actually convert it because have not stored it, you should do num = int(num) because those are functions that return what to want, to really understand how they works mean you should search about dynamically typed languages and functions

How to convert comma separated strings into integers?

I have a dictionary:
dic = {"0.0.1": "112,4,087", "00print_lol": "29,551", "021": "2,541", "02":"23"}
The keys are package names and their values are download counts. But the values can't be converted directly into integers as they are separated by comma.
So, if I use int(dic["0.0.1"]), it gives me en error (which is obvious).
I am doing:
for k,v in dic.items():
temp = ""
for num in v.split(","):
temp += num
dic[k] = int(temp)
print(dic)
Which gives me {'0.0.1': 1124087, '00print_lol': 29551, '021': 2541, '02': 23} and it is the expected result.
Could you please let me know if there is any better way of doing this?

Python3 TypeError: list indices must be integers or slices, not str

i have the task to get the String 'AAAABBBCCDAABBB' into a list like this: ['A','B','C','D','A','B']
I am working on this for 2 hours now, and i can't get the solution. This is my code so far:
list = []
string = 'AAAABBBCCDAABBB'
i = 1
for i in string:
list.append(i)
print(list)
for element in list:
if list[element] == list[element-1]:
list.remove(list[element])
print(list)
I am a newbie to programming, and the error "TypeError: list indices must be integers or slices, not str" always shows up...
I already changed the comparison
if list[element] == list[element-1]
to
if list[element] is list[element-1]
But the error stays the same. I already googled a few times, but there were always lists which didn't need the string-format, but i need it (am i right?).
Thank you for helping!
NoAbL
First of all don't name your variables after built in python statements or data structures like list, tuple or even the name of a module you import, this also applies to files. for example naming your file socket.py and importing the socket module is definitely going to lead to an error (I'll leave you to try that out by yourself)
in your code element is a string, indexes of an iterable must be numbers not strings, so you can tell python
give me the item at position 2.
but right now you're trying to say give me the item at position A and that's not even valid in English, talk-less of a programming language.
you should use the enumerate function if you want to get indexes of an iterable as you loop through it or you could just do
for i in range(len(list))
and loop through the range of the length of the list, you don't really need the elements anyway.
Here is a simpler approach to what you want to do
s = string = 'AAAABBBCCDAABBB'
ls = []
for i in s:
if ls:
if i != ls[-1]:
ls.append(i)
else:
ls.append(i)
print(ls)
It is a different approach, but your problem can be solved using itertools.groupby as follows:
from itertools import groupby
string = 'AAAABBBCCDAABBB'
answer = [group[0] for group in groupby(string)]
print(answer)
Output
['A', 'B', 'C', 'D', 'A', 'B']
According to the documentation, groupby:
Make an iterator that returns consecutive keys and groups from the iterable
In my example we use a list comprehension to iterate over the consecutive keys and groups, and use the index 0 to extract just the key.
You can try the following code:
list = []
string = 'AAAABBBCCDAABBB'
# remove the duplicate character before append to list
prev = ''
for char in string:
if char == prev:
pass
else:
list.append(char)
prev = char
print(list)
Output:
['A', 'B', 'C', 'D', 'A', 'B']
In your loop, element is the string. You want to have the index.
Try for i, element in enumerate(list).
EDIT: i will now be the index of the element you're currently iterating through.

Resources