Questions tagged [defaultdict]

A subclass of Python's dict class that allows to specify a default factory to use for missing keys.

This tag would be applicable to Python questions related with the instantiation, filling and subclassing of the collections.defaultdict class.

defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class.

collections.defaultdict([default_factory[, ...]])

The first argument provides the initial value for the default_factory attribute; it defaults to None. Commonly used default_factories are int, list or dict.

>>> 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])]

this is equivalent to:

>>> d = dict()
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...

http://docs.python.org/library/collections.html

647 questions
-1
votes
3 answers

appending to keys in a defaultdict gives unexpected results

from collections import defaultdict phn_dictionary = {"actual": [], "predicted": []} phn_dict = defaultdict(lambda: phn_dictionary) phn_dict["qwe"]["actual"].extend([123,456]) phn_dict >>>defaultdict(>, {'qwe':…
Usama Arif
  • 11
  • 1
-1
votes
3 answers

Getting the n element of each list in a defaultdict

I have a defaultdict(list) of: d_int = defaultdict(type, {0: [1,2,3,4,5], 1: [6,7,8,9,10], 2: [11,12,13,14,15]}) Is there a pythonic way to save each n element in each list into a new array so I have something like this?: a = [1,6,11] b =…
-1
votes
1 answer

Filtering defaultdict with dictionary comprehension

I have a defaultdict where keys are a number and values are lists with two entries each. I want to filter by a condition based on the first entry. I tried using the suggestion here: filter items in a python dictionary where keys contain a…
-1
votes
1 answer

pop a key, value from values of a key in defaultdict(list) in python

I have a defaultdict(lambda: defaultdict(list)) jenkins_job_dict = defaultdict( at 0x10428b230> , { 'newswires': defaultdict( , { 'commodities': ['blue_virginia', 'green_virginia'], …
Scooby
  • 3,371
  • 8
  • 44
  • 84
-1
votes
1 answer

Multi-level defaultdict with variable depth and with list and int type

I am trying to create a multi-level dict with variable depth and with list and int type. Data structure is like below A --B1 -----C1=1 -----C2=[1] --B2=[3] D --E ----F ------G=4 In the case of above data structure, the last value can be an int or…
Arijit Panda
  • 1,581
  • 2
  • 17
  • 36
-1
votes
2 answers

Grouping tuples within a lists

I have a set of tuples within a list in which I am trying to group the similar items together. Eg. [('/Desktop/material_design_segment/arc_01.texture', 'freshnel_intensity_3.0022.jpg'), ('/Desktop/material_design_segment/arc_01.texture',…
yan
  • 631
  • 9
  • 30
-1
votes
2 answers

While iterating over dictionary, remove elements not required and move further in dictionary(Python)

My concern here is if name_3[0]>50, add it to html table and if name_3[0]<=50, discard it and iterate to next value in dictionary because I don't want to add entry below 50. Below is the logic which I think of. But can we iterate through next value…
Jay
  • 13
  • 1
  • 6
-1
votes
1 answer

how collections.defaultdict.get work in max statement's key paramter--- python

I have read these post 1, 2, 3, but I still can not figure out following python code: >>> s = 'mississippi' >>> d = defaultdict(int) >>> for k in s: ... d[k] += 1 ... >>> lis = ['m', 'i', 's', 'p'] >>> max(lis, key=d.get) 'i' I know the times…
sydridgm
  • 1,012
  • 4
  • 16
  • 30
-1
votes
1 answer

Default Dict append Attribute Error 'float' object has no attribute 'append'

I have read all the script from default dict and all the posts on here. I believe my syntax is correct. influenceDict = defaultdict(list) to fill with all tags from all tweets Later, I am appending ALOT of float values, 1000+ list entries for a…
-1
votes
2 answers

Python: Sort default dictionary of lists

I have dictionary of lists that I need to sort by the first value in the list. I'm using a defaultdict. from collections import defaultdict Dict = defaultdict(list) Dict['A'].append([100, 'abcd']) Dict['A'].append([50,…
user2165857
  • 2,530
  • 7
  • 27
  • 39
-1
votes
2 answers

TypeError: first argument must be callable

fs = codecs.open('grammar_new.txt', encoding='utf-8') unidata=[] d={} fr=codecs.open('rule.txt', 'w') for line in fs: line_data=line.split() for i in range(0,len(line_data)): unidata.append(line_data[i]) d =…
Dhanya
  • 35
  • 1
  • 1
  • 6
-1
votes
2 answers

What is the pythonic way to reverse a defaultdict(list)?

What is the pythonic way to reverse a defaultdict(list)? I could iterating through the defaultdict and creating a new defaultdict. Is there any other way? Is this pythonic: >>> from collections import defaultdict >>> x = defaultdict(list) >>> y =…
alvas
  • 115,346
  • 109
  • 446
  • 738
-2
votes
1 answer

error in dictionary , could not find why i cannot add c

from collections import defaultdict # Defining the dict and passing # lambda as default_factory argument d = defaultdict(lambda c: "Not Present") d["a"] = 1 d["b"] = 2 print(d["a"]) print(d["b"]) print(d["c"]) I expected a right…
-2
votes
1 answer

Remove dict items if key matches with pattern from list

I have a list of patterns : ['transcript/123', 'transcript/127', 'transcript/344', 'transcript/346', 'transcript/245', 'transcript/129', ] I need to loop over all the patterns and look if those patterns match with key names of a dict…
Paillou
  • 779
  • 7
  • 16
-2
votes
1 answer

KeyError(Key) when using append with defaultdict

I am getting the following error when I am trying to append to a dictionary using defaultdict(list). From my understanding, defaultdict is suppose to prevent a keyerror. raise KeyError(key) from err KeyError: 'id' The following is my…
pandoo
  • 3
  • 6