Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to either create a list, or append to it if one already exists?

Tags:

python

list

People also ask

Which is the faster method on a list append or insert?

Insert is slower when compared to append.

Which method is used to add another list to an existing list?

You can use the extend() method to add another list to a list, i.e., combine lists. All items are added to the end of the original list. You may specify other iterable objects, such as tuple . In the case of a string ( str ), each character is added one by one.

What are append () and extend () list methods?

Python append() method adds an element to a list, and the extend() method concatenates the first list with another list (or another iterable). When append() method adds its argument as a single element to the end of a list, the length of the list itself will increase by one.

Is += list the same as append?

For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.


See the docs for the setdefault() method:

setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

You can use this as a single call that will get b if it exists, or set b to an empty list if it doesn't already exist - and either way, return b:

>>> key = 'b'
>>> val = 'a'
>>> print d
{}
>>> d.setdefault(key, []).append(val)
>>> print d
{'b': ['a']}
>>> d.setdefault(key, []).append('zee')
>>> print d
{'b': ['a', 'zee']}

Combine this with a simple "not in" check and you've done what you're after in three lines:

>>> b = d.setdefault('b', [])
>>> if val not in b:
...   b.append(val)
... 
>>> print d
{'b': ['a', 'zee', 'c']}

Assuming you're not really tied to lists, defaultdict and set are quite handy.

import collections
d = collections.defaultdict(set)
for a, b in mappings:
    d[b].add(a)

If you really want lists instead of sets, you could follow this with a

for k, v in d.iteritems():
    d[k] = list(v)

And if you really want a dict instead of a defaultdict, you can say

d = dict(d)

I don't really see any reason you'd want to, though.


Use collections.defaultdict

your_dict = defaultdict(list)
for (a,b) in your_list:
    your_dict[b].append(a)

you can sort your tuples O(n log n) then create your dictionary O(n)

or simplier O(n) but could impose heavy load on memory in case of many tuples:

your_dict = {}
for (a,b) in your_list:
    if b in your_dict:
        your_dict[b].append(a)
    else:
        your_dict[b]=[a]

Hmm it's pretty much the same as you've described. What's awkward about that?

You could also consider using an sql database to do the dirty work.


Instead of using an if, AFAIK it is more pythonic to use a try block instead.

your_list=[('a',1),('a',3),('b',1),('f',1),('a',2),('z',1)]

your_dict={}
for (a,b) in your_list:
    try:
        your_dict[b].append(a)
    except KeyError:
        your_dict[b]=[a]

print your_dict