A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.
The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.
The items() method returns a view of the dictionary in the form of a list of tuples, each tuple being a single key-value pair.
>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}
Why you are getting the ValueError: dictionary update sequence element #0 has length 1916; 2 is required
error:
The answer is that the elements of your list are not what you think they are. If you type myList[0]
you will find that the first element of your list is not a two-tuple, e.g. ('A', 1)
, but rather a 1916-length iterable.
Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]
), all you need to do is dict(myList)
.
[2021 edit: now also answers the actual question asked, not the intended question about the specific error:]
Either use the usual dict(iterableOrMapping)
constructor, or use the dict comprehension {someExpr(k,v) for k:v in iterable}
syntax:
>>> example1 = [('A',1), ('B',2), ('C',3)]
>>> dict(example1)
{'A': 1, 'B': 2, 'C': 3}
>>> {x:x**2 for x in range(3)}
{0: 0, 1: 1, 2:4}
# inline; same as example 1 effectively. may be an iterable, such as
# a sequence, evaluated generator, generator expression
>>> dict( zip(range(2),range(2)) )
{0: 0, 1: 1, 2:2}
A Python dictionary is an O(1)-searchable unordered collection of pairs {(k
ey→v
alue), ...} where keys are any immutable objects and values are any object.
Keys MUST implement the .__eq__()
and .__hash__()
methods to be usable in the dictionary. If you are thinking of implementing this, you are likely doing something wrong and should maybe consider a different mapping data structure! (Though sometimes you can get away with wrapping the keys in a different wrapper structure and using a regular dict, this may not be ideal.)
Intermediate or advanced programmers who wish to implement a 'frozen' or 'immutable' type, or one which masquerades as one, must be very careful of implications or else your program will be wrong with extremely subtle and near-impossible-to-find bugs:
You can't use a dict if you allow yourself to mutate the object later such that its notion of equality might change. Objects considered equal must always have __eq__
return True and have __hash__
return identical values.
The methods must exactly obey the spec. This means that:
hash(x)==hash(y)
means x
MIGHT equal y
and the internal python code must then check x==y
(.__eq__
) to confirm it's a true-positive and not a false-positive. This allows O(1) lookup.__hash__
value not change for any reason once the object is in its final state. If you cannot guarantee both this and hash(x)!=hash(y) implies x!=y
, you should not be using a dict.
Python has a bunch of built-in frozen datastructures such as namedtuple
, frozenset
, etc., but they are sometimes harder to work with. tuple
is the basic frozen variant of the basic list
structure (which would let you store a {(1, 2): 3, (4, 5): 6}
). It also has some variants of the dict
structure. If you want to get a map from "frozen dicts" to values, frozendict doesn't exist except as a third-party library, but you can extract the dict's .items()
as a an unordered frozenset
of tuple
s.
Have you tried this?
>>> l=[('A',1), ('B',2), ('C',3)]
>>> d=dict(l)
>>> d
{'A': 1, 'C': 3, 'B': 2}
Here is a way to handle duplicate tuple "keys":
# An example
l = [('A', 1), ('B', 2), ('C', 3), ('A', 5), ('D', 0), ('D', 9)]
# A solution
d = dict()
[d [t [0]].append(t [1]) if t [0] in list(d.keys())
else d.update({t [0]: [t [1]]}) for t in l]
d
OUTPUT: {'A': [1, 5], 'B': [2], 'C': [3], 'D': [0, 9]}
If Tuple has no key repetitions, it's Simple.
tup = [("A",0),("B",3),("C",5)]
dic = dict(tup)
print(dic)
If tuple has key repetitions.
tup = [("A",0),("B",3),("C",5),("A",9),("B",4)]
dic = {}
for i, j in tup:
dic.setdefault(i,[]).append(j)
print(dic)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With