How to use 'python tuple to dict' in Python

Every line of 'python tuple to dict' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
13def convertTupleListToDict(list_of_tuples):
14 dictToReturn = {}
15 for item in list_of_tuples:
16 if item[0] not in dictToReturn:
17 index_list = []
18 index_list.append(item[1])
19 dictToReturn[item[0]] = index_list
20 else:
21 dictToReturn[item[0]].append(item[1])
22 return dictToReturn
18def namedtuple_to_dict(obj):
19 if isinstance(obj, Tensor):
20 return obj.item()
21 if hasattr(obj, "_asdict"): # detect namedtuple
22 return dict(zip(obj._fields, (namedtuple_to_dict(item) for item in obj)))
23 elif isinstance(obj, str): # iterables - strings
24 return obj
25 elif hasattr(obj, "keys"): # iterables - mapping
26 return dict(
27 zip(obj.keys(), (namedtuple_to_dict(item) for item in obj.values()))
28 )
29 elif hasattr(obj, "__iter__"): # iterables - sequence
30 return type(obj)((namedtuple_to_dict(item) for item in obj))
31 else: # non-iterable cannot contain namedtuples
32 return obj

Related snippets