Answers for "default dict python"

1

python default dictonary

from collections import defaultdict

d_int = defaultdict(int)
d_list = defaultdict(list)

def foo():
  return 'default value'
 
d_foo = defaultdict(foo)

>>> d_int
defaultdict(<type 'int'>, {})
>>> d_list
defaultdict(<type 'list'>, {})
>>> d_foo
defaultdict(<function foo at 0x7f34a0a69578>, {})
Posted by: Guest on October-31-2021
1

python defaultdict to dict

>>> #You can simply call dict:
>>> a
defaultdict(<type 'list'>, {'1': ['b', 'a'], '3': ['b'], '2': ['a']})
>>> dict(a)
{'1': ['b', 'a'], '3': ['b'], '2': ['a']}

# but remember that a defaultdict is a dict
# (with some special behavior, check source):
>>> isinstance(a, dict)
True
Posted by: Guest on October-13-2020
1

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])]
Posted by: Guest on April-06-2020

Python Answers by Framework

Browse Popular Code Answers by Language