Home > Mobile >  How to turn a string into a dictionary in python based on every other element
How to turn a string into a dictionary in python based on every other element

Time:10-04

I start with this original string

"
AB
BC
CD
DA
EA
AF
"

and I turn it into this "ABBCCDDAEAAF". I want to turn it into a dictionary like this: {A: "B, F", B: "C", C: "D", D: "A", E: "A"}. Is there a way I can do this without a loop? Thanks in advance.

CodePudding user response:

Try This;

string = "ABBCCDDAEAAF"
n = 2
string_out = [(string[i:i n]) for i in range(0, len(string), n)]

dct = {}
for i in string_out:
    if i[0] in dct.keys():
        dct[i[0]] = dct[i[0]]   ","   i[1]
    else:
        dct[i[0]] = i[1]
    
print(dct)

# {'A': 'B,F', 'B': 'C', 'C': 'D', 'D': 'A', 'E': 'A'}

CodePudding user response:

I don't know why you don't want to use for loop because directly or indirectly you will be using for loop

Here is the solution without using for keyword

from itertools import groupby
a = " AB BC CD DA EA AF "
res_dict = dict(map(lambda x: [x[0], ', '.join(map(lambda a: a[-1], x[1])) ], groupby(sorted(map(lambda x: [x[0], x[1]], a.strip().split()), key=lambda x:x[0]), key=lambda x: x[0])))
# output = {'A': 'B, F', 'B': 'C', 'C': 'D', 'D': 'A', 'E': 'A'}
  • Related