Reputation: 1568
I have a list made of a python dictionary keys via; list(dict.keys())
.
dict.keys()
dict_keys(['South', 'North'])
I would like to add a string to the every element in the list = ['South', 'North']
like:
my_string = 'to_'
In the end I want to have list = ['to_South', 'to_North']
Is there a method I could use for this?
something like:
list.add_beginning_of_each_element('to_')
Upvotes: 9
Views: 17474
Reputation: 1545
You can use lambda function:
lst = ['South', 'North']
result = list(map(lambda x: 'to_' + x, lst))
Upvotes: 5
Reputation: 71560
Or map
:
>>> l = ['South', 'North']
>>> list(map('to_'.__add__,l))
['to_South', 'to_North']
>>>
There a add_prefix
in pandas
, so if you have a pandas dataframe, you can just use add_prefix
to add to the columns, an example of making a dataframe out of a list and having them as columns:
>>> import pandas as pd
>>> pd.DataFrame(columns=['South', 'North']).add_prefix('to_').columns.tolist()
['to_South', 'to_North']
Upvotes: 11
Reputation: 61910
Use a list comprehension:
lst = ['South', 'North']
result = ['to_' + direction for direction in lst]
As an alternative you could use map:
def add_to_beginning(s, start='to_'):
return start + s
lst = ['South', 'North']
result = list(map(add_to_beginning, lst))
print(result)
Upvotes: 14
Reputation: 81594
dict.keys()
does not return the actual keys, it merely returns a view (=copy) of the keys.
If you want to print a modified version of the keys:
print(['to_' + key for key in d.keys()])
If you want to change the actual keys:
d = {'to_' + key: value for key, value in d.items()}
Upvotes: 1