By using the zip() and dict() method we will create a dictionary from two lists.
The easiest way to create a dictionary from a list of keys and values is to apply the dict() function and inside the function take the zip() method as an argument.
Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.
You can use defaultdict:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = ['1', '2']
>>> for i in a:
... for j in range(int(i), int(i) + 2):
... d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]
You can build it with list comprehension like this:
>>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2'])
{'1': [1, 2], '2': [2, 3]}
And for the second part of your question use defaultdict
>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
You can use setdefault
:
d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d.setdefault(j, []).append(i)
print d # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}
The rather oddly-named setdefault
function says "Get the value with this key, or if that key isn't there, add this value and then return it."
As others have rightly pointed out, defaultdict
is a better and more modern choice. setdefault
is still useful in older versions of Python (prior to 2.5).
Personally, I just use JSON to convert things to strings and back. Strings I understand.
import json
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
mydict = {}
hash = json.dumps(s)
mydict[hash] = "whatever"
print mydict
#{'[["yellow", 1], ["blue", 2], ["yellow", 3], ["blue", 4], ["red", 1]]': 'whatever'}
Your question has already been answered, but IIRC you can replace lines like:
if d.has_key(scope_item):
with:
if scope_item in d:
That is, d
references d.keys()
in that construction. Sometimes defaultdict
isn't the best option (for example, if you want to execute multiple lines of code after the else
associated with the above if
), and I find the in
syntax easier to read.
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