How to convert comma separated strings into integers? - python-3.x

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?

Related

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

Remove double quotes from a string in python

Would like my output which should not be string but my code returning string to me. Please look on my below code in which z is my output. I tried with regex, replace, strip, eval, ast.literal_eval but nothing worked for me as of now.
x = "'yyyymm'='202005','run_id'='51',drop_columns=run_id"
y = x.split(',')
print(y)
This will print:
["'yyyymm'='202005'","'run_id'='51'","drop_columns=run_id"]`
But I want:
['yyyymm'='202005','run_id'='51',drop_columns=run_id]
x is a string and if you split a string, you will get an array of strings. It is basically cutting it into pieces.
Your question is not really clear on what you want to achieve. If you want to have key-value-pairs, you'd need to split each token at the =. This would give you something like this:
[('yyyymm', '202005'), ('run_id', '51'), ('drop_columns', 'run_id')]
But the items in the tuples would still be strings. If you want to have integers, you would need to cast them which is only possible if the strings consist of digits. It would not be possible to cast 'run_id' to integer.
You can refer to this example. I'm not sure if that is 100% what you are looking for, but it should give you the correct idea.
x = "yyyymm=202005,run_id=51,drop_columns=run_id"
y = x.split(',')
tmp = []
for e in y:
tmp.append((e.split('=')[0], e.split('=')[1]))
out = []
for e in tmp:
if str.isnumeric(e[1]):
out.append((e[0], int(e[1])))
else:
out.append(e)
print(out)
This will give you:
[('yyyymm', 202005), ('run_id', 51), ('drop_columns', 'run_id')]

Convert elements in ONE list to keys and values in a dictionary

I'm looking for a way to convert a list to a dictionary as shown below. Is this possible? Thanks in advance.
list = ["1/a", "2/b", "3/c"]
dict = {"1": "a", "2": "b", "3": "c"}
Of course it is possible.
First, you can split an element of the list with e.split("/"), which will give a list for example splitted = ["1", "a"].
You can assign the first element to the key and the second to the value:
k = splitted[0]
v = splitted[1]
or another way to express that:
k,v = splitted
Then you can iterate over your list to build your dict, so if we wrap this up (you should not call a list list because list is a type and an already existing identifier:
d = {}
for e in elements:
k,v = e.split("/")
d[k] = v
You can also do that in one line with a dict comprehension:
d = {k:v for k,v in [e.split("/") for e in elements]}
Yes you can.
If you want to have everything after the '/' (i.e. 2nd char), you can do:
dict = {c[0]:c[2:] for c in list}
If you want to have everything after the '/' (but may not be the 2nd char), you can do:
dict = {c[0]:c.split('/')[1] for c in list}
It really dependes on the input you have and what output you want
You can do like this.
lista = ["1/a", "2/b", "3/c"]
new_dict = {}
for val in lista:
new_dict.update({val[0]:val[2]})
print(new_dict)
Try this
list = ["1as/aasc", "2sa/bef", "3edc/cadeef"]
dict = {i.split('/')[0]:i.split('/')[1] for i in list}
Answer will be
{'1as': 'aasc', '2sa': 'bef', '3edc': 'cadeef'}
I have given a different test case. Hope this will answer your question.

How to slice a list of strings till index of matched string depending on if-else condition

I have a list of strings =
['after','second','shot','take','note','of','the','temp']
I want to strip all strings after the appearance of 'note'.
It should return
['after','second','shot','take']
There are also lists which does not have the flag word 'note'.
So in case of a list of strings =
['after','second','shot','take','of','the','temp']
it should return the list as it is.
How to do that in a fast way? I have to repeat the same thing with many lists with unequal length.
tokens = [tokens[:tokens.index(v)] if v == 'note' else v for v in tokens]
There is no need of an iteration when you can slice list:
strings[:strings.index('note')+1]
where s is your input list of strings. The end slice is exclusive, hence a +1 makes sure 'note' is part.
In case of missing data ('note'):
try:
final_lst = strings[:strings.index('note')+1]
except ValueError:
final_lst = strings
if you want to make sure the flagged word is present:
if 'note' in lst:
lst = lst[:lst.index('note')+1]
Pretty much the same as #Austin's answer above.

How to edit lists using input function

I am trying to edit and fill the lists in A, B and C using the input function.
A = ['']
B = ['']
C = ['']
key = input()
key[0] = 'X'
But i get this error.
TypeError: 'str' object does not support item assignment
How can i use the input function to edit my list. Or you might have better way to do this?
Thank You!
The strings per se in Python are immutable (you can't modify its content) however what you can do is to store them in a char list and a list in python is a mutable object, hence you can modify the char list as you see fit.
key = input() # "hello"
new_key = list(key) # ['h','e','l','l','o']
new_key[0] = 'X' # ['X','e','l','l','o']
Python strings are immutable objects which means you cannot change an existing string. The best you can do is create a new string that is a variation on the original. For e.g :
newstring = 'newchar' + oldstring[1:]
In your case it would be something like:
key = input()
newkey = 'X' +key[1:]
Solved. instead of using lists, better use dictionary to fill the A, B or C.
var = {'A':' ', 'B':' ', 'C':' '}
var[input()] = 'X'
Thanks for all of your participation!

Resources