List of tuples to dictionary
Just call dict()
on the list of tuples directly
>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}
Converting a list of tuples into a dict
l = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
d = {}
for x, y in l:
d.setdefault(x, []).append(y)
print d
produces:{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}
Convert list of tuples into a dictionary with list of tuples
A couple of list comprehensions and Bob's your uncle:
original_list = [
(5, 10, 8, 2, 3, 12, "first", "second", 2, 80, 75, "third"),
(8, 2, 8, 14, 7, 3, "name", "last", 2, 80, 75, "block"),
]
new = {
"specs": [tuple(l[:6]) for l in original_list],
"data": [tuple(l[6:]) for l in original_list],
}
print(new)
outputs{
'specs': [(5, 10, 8, 2, 3, 12), (8, 2, 8, 14, 7, 3)],
'data': [('first', 'second', 2, 80, 75, 'third'), ('name', 'last', 2, 80, 75, 'block')]
}
How to convert list of key-value tuples into dictionary?
Your error:
Why you are getting theValueError: 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:]
In general:
Either use the usualdict(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:
- For novices: Hash functions(wikip.) let you get a false-positive or true-positive result;
hash(x)==hash(y)
meansx
MIGHT equaly
and the internal python code must then checkx==y
(.__eq__
) to confirm it's a true-positive and not a false-positive. This allows O(1) lookup. - For novices: It is critically important that the
__hash__
value not change for any reason once the object is in its final state. If you cannot guarantee both this andhash(x)!=hash(y) implies x!=y
, you should not be using a dict. - One might consider a different type of mapping rather than modifying the data itself. This can be equivalent to writing a wrapper object, at the cost of using a library. This is usually not necessary.
- For experts: It should also be noted that the hashes of some default objects are salted and may change between python invocations and versions (this may be a gotcha if you store or network-communicate data in any way that contains python hashes; they are an internal detail that should be regenerated on each process startup).
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. Converting list of tuples into a dictionary
>>> from collections import defaultdict
>>> l= [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> d= defaultdict( list )
>>> for v, k in l:
... d[k].append(v)
...
>>> d
defaultdict(<type 'list'>, {23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]})
>>> [ {k:d[k]} for k in sorted(d) ]
[{4: [1, 2, 3]}, {15: [4, 5, 9, 11, 12]}, {23: [6, 7, 8, 10]}]
Convert 3-Element List of Tuples to Dictionary
You can use something like this:
>>> x = [(1, 'al', 10), (2, 'bob', 20), (3, 'cam', 30)]
>>> dict([(a, (b, c)) for a, b, c in x])
{1: ('al', 10), 2: ('bob', 20), 3: ('cam', 30)}
Passing in a list of 2-tuples to dict()
will give a dict
using the first item in the tuple as the key and the second item as the value.
Related Topics
Create Spark Dataframe. Can Not Infer Schema for Type
How to Crop the Internal Area of a Contour
Broken References in Virtualenvs
How to Fix Selenium Webdriverexception: the Browser Appears to Have Exited Before We Could Connect
Get the String Within Brackets in Python
In Python, Why Is List[] Automatically Global
Cannot Redirect Output When I Run Python Script on Windows Using Just Script's Name
How to Tell Pycharm What Type a Parameter Is Expected to Be
How to Limit the Maximum Value of a Numeric Field in a Django Model
Numpy Version of "Exponential Weighted Moving Average", Equivalent to Pandas.Ewm().Mean()
How to Restrict Foreign Keys Choices to Related Objects Only in Django
How to Get the Ip Address from a Http Request Using the Requests Library
Overflowerror: (34, 'Result Too Large')
Print to the Same Line and Not a New Line
Matplotlib: How to Show a Figure That Has Been Closed
How to Customize Title Bar and Window of Desktop Application
How to Get Windows' Special Folders for Currently Logged-In User