+ 1

# python dic

how can i separate a key in dic that is string for example i have dic like below: a = {"10":1 , "21":14} i want to separate 1 and 0 and separate 2 and 1

14th Jun 2020, 9:19 AM
nima rasi
+ 2
As a normal for-loop it would look like this: b = [] for key in a: sublist = [] for digit in key: sublist.append(int(digit)) sublist.append(a[key]) b.append(sublist) With comprehensions, you get rid of the in-between lists, the appending happens implicitly, and the order is different. Comprehensions in all their shapes are quite convenient. Maybe you want to read this: https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
14th Jun 2020, 12:09 PM
HonFu
+ 2
@HouFu look i want to separate key and save in a matrix b is a array in this case like that b = [[1 , 0 , 1] , [2, 1 ,14]] b[0][3] = 1 is value of key '10' b[1][3] = 14 is value of key '21'
14th Jun 2020, 9:40 AM
nima rasi
+ 2
@HonFu Thanks a lotttt
14th Jun 2020, 12:15 PM
nima rasi
+ 1
What will the new keys contain? Can you show how the dict will look after that?
14th Jun 2020, 9:28 AM
HonFu
+ 1
@HonFu i dont want to change the keys i just want to use the keys but i want to separate them to use
14th Jun 2020, 9:29 AM
nima rasi
+ 1
nima x, but if you separate them, you will have two keys, where there was one before. What value will the additional key get?
14th Jun 2020, 9:36 AM
HonFu
+ 1
If you just need the digits as str: b = [list(key)+[a[key]] for key in a] If the digits have to be actual integers: b = [[int(digit) for digit in key] + [a[key]] for key in a]
14th Jun 2020, 9:46 AM
HonFu
+ 1
AmgKhvbbi Schweppes, this is not your question thread. Please follow the forum rules and only post ontopic. https://www.sololearn.com/discuss/1316935/?ref=app
14th Jun 2020, 10:14 AM
HonFu
+ 1
@Kiibo Ghayal @Honfu thanks Honfu it works but can you explain this list comprehension i have problem in understanding it b = [[int(digit) for digit in key] + [a[key]] for key in a]
14th Jun 2020, 11:51 AM
nima rasi