Posts: 5
Threads: 4
Joined: Sep 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.
Posts: 2,342
Threads: 62
Joined: Sep 2016
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.
Posts: 443
Threads: 1
Joined: Sep 2018
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)
Posts: 67
Threads: 17
Joined: Aug 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'}
A.D.Tejpal
Posts: 1,950
Threads: 8
Joined: Jun 2018
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)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
|