0

I have a working code:

def after_tasks(visits):
   return {task: {name for name, ta in visits if ta == task} for name, task in visits}

And the code returns something in the format like: {"taskexample": {"something",...}}
But i want a code to return something like {{"something",..}}, without "taskexample": on the beginning.
How do i achive that? Plus it needs to be written in one line like the code above.

The visits structure is:

   [("Ana", "coffe"), 
     ("Berta", "coffe"), 
     ("Cilka", "exercise"),
     ("Dani", "doctor")]
3
  • You are returning a dictionary Commented Dec 1, 2020 at 10:42
  • How is your 'visits' structure look like? Commented Dec 1, 2020 at 10:43
  • added the visits structure Commented Dec 1, 2020 at 10:47

1 Answer 1

2

Understanding and using dict

Your function after_task, as it is currently written, returns a dict (for "dictionary"). This is a standard python class which associates keys and values. You can iterate over a dict using .keys(), .values() or .items():

d = {'a': 'Alice'; 'b': 'Bob'; 'c': 'Chong'}

for k in d.keys():
  print(k)

for v in d.values():
  print(v)

for k,v in d.items():
  print('{}: {}'.format(k, v))

Fixing your code

If I understand your question correctly, your problem is that your function is returning a dict, but you want to return simply the list of values in the dict, rather than associations key:value.

You can do that with d.values():

def after_tasks(visits):
   d = {task: {name for name, ta in visits if ta == task} for name, task in visits}
   return list(d.values())

print(after_tasks([("Ana", "coffe"), ("Berta", "coffe"), ("Cilka", "exercise"), ("Dani", "doctor")]))
# [{'Ana', 'Berta'}, {'Cilka'}, {'Dani'}]

Completely different code for the same problem

This is another suggestion using itertools.groupby.

import itertools
import operator

def after_tasks(visits):
  return [[name for task,name in g] for k,g in itertools.groupby(sorted([(k,v) for v,k in visits]), key=operator.itemgetter(0))]

print(after_tasks([("Ana", "coffe"), ("Berta", "coffe"), ("Cilka", "exercise"), ("Dani", "doctor")]))
# [['Ana', 'Berta'], ['Dani'], ['Cilka']]

Relevant documentation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.