Python extend for a dictionary
a.update(b)
Latest Python Standard Library Documentation
Append a dictionary to a dictionary
You can do
orig.update(extra)
or, if you don't want orig
to be modified, make a copy first:
dest = dict(orig) # or orig.copy()
dest.update(extra)
Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,
>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}
How to extend values in dictionaries using key in Python
You should initialize d
as an empty dict instead, so that you can iterate through l
and the key-value pairs to keep appending the values to the sub-list of d
at the given keys:
l = [
{'a': (23, 48), 'b': 34, 'c': "fame", 'd': "who"},
{'a': (94, 29), 'b': 3, 'c': "house", 'd': "cats"},
{'a': (23, 12), 'b': 93, 'c': "imap", 'd': "stack"},
]
d = {}
for s in l:
for k, v in s.items():
d.setdefault(k, []).append(v)
d
becomes:
{'a': [(23, 48), (94, 29), (23, 12)],
'b': [34, 3, 93],
'c': ['fame', 'house', 'imap'],
'd': ['who', 'cats', 'stack']}
If the sub-dicts in l
may contain other keys, you can instead initialize d
as a dict of empty lists under the desired keys:
l = [
{'a': (23, 48), 'b': 34, 'c': "fame", 'd': "who"},
{'a': (94, 29), 'b': 3, 'c': "house", 'd': "cats"},
{'a': (23, 12), 'b': 93, 'c': "imap", 'd': "stack"},
{'e': 'choices'}
]
d = {k: [] for k in ('a', 'b', 'c', 'd')}
for s in l:
for k in d:
d[k].append(s.get(k))
in which case d
becomes:
{'a': [(23, 48), (94, 29), (23, 12), None],
'b': [34, 3, 93, None],
'c': ['fame', 'house', 'imap', None],
'd': ['who', 'cats', 'stack', None]}
Python:Extend the 'dict' class
You can either subclass dict
or UserDict
, since van already talked about UserDict, lets look at dict
.
Type help(dict)
into an interpreter and you see a big list of methods. You will need to override all the methods that modify the dict as well as the methods that iterate over the dict.
Methods that modify the dict include __delitem__
,__setitem__
,clear
etc.
Methods that iterate the dict include __iter__
,keys
,values
,items
etc.
This should get you started
>>> class odict(dict):
... def __init__(self, *args, **kw):
... super(odict,self).__init__(*args, **kw)
... self.itemlist = super(odict,self).keys()
... def __setitem__(self, key, value):
... # TODO: what should happen to the order if
... # the key is already in the dict
... self.itemlist.append(key)
... super(odict,self).__setitem__(key, value)
... def __iter__(self):
... return iter(self.itemlist)
... def keys(self):
... return self.itemlist
... def values(self):
... return [self[key] for key in self]
... def itervalues(self):
... return (self[key] for key in self)
...
>>> od = odict(a=1,b=2)
>>> print od
{'a': 1, 'b': 2}
>>> od['d']=4
>>> od['c']=3
>>> print od # look at the `__str__` and `__repr__` methods
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> print od.keys()
['a', 'b', 'd', 'c']
>>> print od.values()
[1, 2, 4, 3]
Python extend dict value to list
dict.__iter__
runs through all the KEYS of the dictionary without giving the values, so for something like:
d = {'a':1, 'b':2, 'c':3}
for element in d:
print(element)
# "a"
# "b"
# "c"
That's why list.extend
is only giving you the keys "errors"
and "filename"
. What would you LIKE it to give you, is the better question? I'm not even sure how that should be expected to work -- maybe a tuple of (key,value)
? To do that, access dict.items()
which will give you a dict_items
object that yields (key,value)
each iteration:
To use the same example:
for element in d.items():
print(element)
# ("a",1)
# ("b",2)
# ("c",3)
Or in your case:
for key,value in cldterr.items():
clderrors.append((key,value))
# or if you want future programmers to yell at you:
# [clderrors.append(key,value) for key,value in cldterr.items()]
# don't use list comps for their side effects! :)
Or simply:
clderrors.extend(cldterr.items())
python list append versus extend for dictionaries
list.extend()
takes an iterable and appends all elements of the iterable. Dictionary by default iterates over its keys, so all the keys are appended to the list.
list.append()
takes the object as is and adds it to the list, which is exactly what happend in your code.
How do I extend the values of a specific dictionary item with overlapping keys?
try this:
def add_name(db, name, gender, year, count, rank=None):
# check if the key (name, gender) in db. if it's in, append
if (name, gender) in db:
db[(name, gender)].append((year, count, rank))
# else new a key
else:
db[(name, gender)] = [(year, count, rank)]
return None
Related Topics
Access Memory Address in Python
Python SQLite Parameter Substitution with Wildcards in Like
Substitute Multiple Whitespace with Single Whitespace in Python
How to Parse Somewhat Wrong JSON with Python
Python - Download Images from Google Image Search
Validating Detailed Types in Python Dataclasses
Python Overwriting Variables in Nested Functions
How to Deal with Kivy Installing Error in Python 3.8
How to Execute a Command Prompt Command from Python
How to Match Any String from a List of Strings in Regular Expressions in Python
How Are Python In-Place Operator Functions Different Than the Standard Operator Functions
Failed to Upload Packages to Pypi: 410 Gone
Flask-Sqlalchemy Import/Context Issue
How to Redirect the Output of Print to a Txt File