Python Forum
Basic one: Aggregating from a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic one: Aggregating from a dictionary
#2
it can probably be done with NumPy too
but there is defaultdict from collections module

from collections import defaultdict
import json
spam = defaultdict(list)
files = {'fle1.txt': 'John', 'file2.txt': 'James', 'file3.txt': 'John'}
for fname, owner in files.items():
    spam[owner].append(fname)
print(spam)

# dump as json
eggs = json.dumps(spam)
print(eggs)
Output:
defaultdict(<class 'list'>, {'John': ['fle1.txt', 'file3.txt'], 'James': ['file2.txt']}) {"John": ["fle1.txt", "file3.txt"], "James": ["file2.txt"]}
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Basic one: Aggregating from a dictionary - by buran - Aug-12-2019, 07:33 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Aggregating CSV Data nb1214 1 1,650 Jun-10-2021, 06:15 PM
Last Post: Axel_Erfurt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020