Home > Back-end >  Prepend a prefix to every element of a list as dictionary values
Prepend a prefix to every element of a list as dictionary values

Time:09-01

I have this dict:

{'q1': [5, 6, 90, 91, 119, 144, 181, 399],
 'q2': [236, 166],
 'q3': [552, 401, 1297, 1296],
}

And I'd like to prepend a 'd' to every element within each value's list:

{'q1': ['d5', 'd6', 'd90', 'd91', 'd119', 'd144', 'd181', 'd399'],
 'q2': ['d236', 'd166'],
 'q3': ['d552', 'd401', 'd1297', 'd1296'],
}

I have tried out = {k: 'd' str(v) for k,v in out.items()} but this only adds the 'd' to the outside of each value's list:

{'q1': d[5, 6, 90, 91, 119, 144, 181, 399],
 'q2': d[236, 166],
 'q3': d[552, 401, 1297, 1296],
}

I imagine I have to do a sort of list comprehension within the dict comprehension, but I am not sure how to implement.

CodePudding user response:

Try:

dct = {
    "q1": [5, 6, 90, 91, 119, 144, 181, 399],
    "q2": [236, 166],
    "q3": [552, 401, 1297, 1296],
}

for v in dct.values():
    v[:] = (f"d{i}" for i in v)

print(dct)

Prints:

{
    "q1": ["d5", "d6", "d90", "d91", "d119", "d144", "d181", "d399"],
    "q2": ["d236", "d166"],
    "q3": ["d552", "d401", "d1297", "d1296"],
}

CodePudding user response:

Try using an f-string in a nested comprehension if you desire to keep your original dict unchanged:

>>> d = {'q1': [5, 6, 90, 91, 119, 144, 181, 399], 'q2': [236, 166], 'q3': [552, 401, 1297, 1296]}
>>> {k: [f'd{x}' for x in v] for k, v in d.items()}
{'q1': ['d5', 'd6', 'd90', 'd91', 'd119', 'd144', 'd181', 'd399'], 'q2': ['d236', 'd166'], 'q3': ['d552', 'd401', 'd1297', 'd1296']}
  • Related