Home > Software design >  Creating dictionary from tuple
Creating dictionary from tuple

Time:03-14

Problem: I am trying to create a dictionary from a tuple but I get the below messages:

Valueerror: dictionary update sequence element #1 has length 3; 2 is required
ValueError: dictionary update sequence element #2 has length 1; 2 is required

I tried using dict() to create the dictionary and this seems to work only when the list of tuples contains two elements.

code:

my_list = [('a', 1), ('b', 2,3), ('c',)]

dict(my_list)

The result I am trying to produce is:

dict(my_list)
{'a': 1, 'b': 2, 'c': None}

CodePudding user response:

You can use following code. It checks for each tuple if a second element exists. If not None is used.

my_list = [('a', 1), ('b', 2,3), ('c',)]

result = {x[0]: x[1] if len(x)>1 else None for x in my_list}
print(result)

Output:

{'a': 1, 'b': 2, 'c': None}
  • Related