Python Forum

Full Version: Converting List into list of tuples
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here I am trying to convert a List into a dictionary. So, I am following this approach.
my_list = ['a', 'A', 'b', 'B', 'c', 'C']

If I convert a list into a multiple tuples (('a', 'A'), ('b', 'B'), ('c', 'C')), then I can easily convert into a dictionary using dict() built in function.

Please guide me to convert a list into multiples of tuples.
Look into zip. I'd create an iterator from your list and zip it with itself, but if that sounds too advanced for you, consider slicing's third parameter to slice your list a couple of times into appropriate input for zip.
If you go with zip(), you'll want to slice the list up into lowercase an uppercase characters to get the desired result.

my_list = ['a', 'A', 'b', 'B', 'c', 'C']
for pair in zip(my_list[::2], my_list[1::2]):
    print(pair)
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E']
my_dict = dict([*zip(my_list[::2], my_list[1::2])])
print(my_dict)
Output:
{'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'}
One can use zip() with iterator as well:

my_list = ['a', 'A', 'b', 'B', 'c', 'C']
dict(zip(*[iter(my_list)]*2))
Python built-in itertools module documentation contains following recipe:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)