Python Forum
Converting List into list of tuples - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Converting List into list of tuples (/thread-21396.html)



Converting List into list of tuples - ARV - Sep-27-2019

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.


RE: Converting List into list of tuples - micseydel - Sep-27-2019

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.


RE: Converting List into list of tuples - stullis - Sep-27-2019

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)



RE: Converting List into list of tuples - adt - Sep-28-2019

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'}



RE: Converting List into list of tuples - perfringo - Sep-28-2019

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)