0

I need to add an in statement, something along the list of list(vs) if type(vs, str)

d={'int':["unit", "bool"], 'timestamp':"pruct"}

{v: k
 for k, vs in d.items()
 for v in vs}

I need this output

{'unit': 'int', 'bool': 'int', 'pruct': 'timestamp'}

but I'm getting

{'unit': 'int',
 'bool': 'int',
 'p': 'timestamp',
 'r': 'timestamp',
 'u': 'timestamp',
 'c': 'timestamp',
 't': 'timestamp'}
Topde
  • 581
  • 5
  • 12
  • If you change your starting dictionary to have ["pruct"]? You are just missing the concept of iterable here. In one case ("unit") the value iterable is a list, in the other ("timestamp") the value iterable is a string. – deponovo Oct 27 '22 at 22:31

3 Answers3

2

In addition to my comment to the original question, here you go:

def listify_if_necessary(x):
    return [x] if isinstance(x, str) else x

{v: k for k, vs in d.items() for v in listify_if_necessary(vs)}

Out:

{'unit': 'int', 'bool': 'int', 'pruct': 'timestamp'}

Note, as wjandrea pointed out, this listify_if_necessary can be replaced by always_iterable().

deponovo
  • 1,114
  • 7
  • 23
  • 2
    [Avoid named lambdas](/q/38381556/4518341), use a `def` instead, or just move the conditional expression into the comprehension like in [itroulli's answer](/a/74229036/4518341). Or use [`always_iterable()`](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable) from `more_itertools`. – wjandrea Oct 27 '22 at 22:56
  • @wjandrea agree with you. It was a fast answer. – deponovo Oct 28 '22 at 13:14
1

If you insist on using dictionary comprehension this should work for you:

{v: k
 for k, vs in d.items()
 for v in ([vs] if type(vs) is str else vs)}

However, do not forget that

Simple is better than complex ... Readability counts

- The Zen of Python

itroulli
  • 2,044
  • 1
  • 10
  • 21
  • 1
    using always_iterable as suggested by @wjandrea is the neatest solution but the question was about how to add a conditional if condition and this answers that as well the scenario provided – Topde Nov 03 '22 at 09:03
0

Here is one way:

new_dict = {}
for key, item in d.items():
    if type(item) is list:
        for i in item:
            new_dict[i] = key
    elif type(item) is str:
        new_dict[item] = key

print(new_dict)

Output: {'unit': 'int', 'bool': 'int', 'pruct': 'timestamp'}