简体   繁体   中英

Creating dictionary from tuple

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}

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM