Kelly Flet
Kelly Flet

Reputation: 564

Access string from dictionary value in Python

I am trying to write a comprehension that, given two dictionaries (f, g), will return a dictionary whose key is the key of f, and whose value is the corresponding key's value of f of the value of g. For example, given:

f = {0: 'a', 1: 'b'}
g = {'a': 'apple', 'b': 'banana'}
my_function_composition(f, g) #returns {0: 'apple', 1: 'banana'}

My comprehension for some reason only outputs one character of the string

#output: {0: 'e', 1: 'a'}

Here is my function:

def my_function_composition(f, g):
    return {key: value for key in f for value in g[f[key]]}

Why is Python returning what seems to be the last character of the value string, rather than the entire string?

Upvotes: 1

Views: 2004

Answers (3)

Gabriel Muj
Gabriel Muj

Reputation: 3805

You can do it like this:

def my_function_composition(f, g):
    return {key: g[value] for key, value in f.items()}

To be safer you can use g.get(value, 0) in case g doesn't have that key and you want a default value like 0.

In case you need only the f values that are in g dictionary you can add extra check for the value.

def my_function_composition(f, g):
    return {key: g[value] for key, value in f.items() if value in g}

Upvotes: 3

Xero Smith
Xero Smith

Reputation: 2076

{key : g.get(f[key], None) for key in f} Compatible with both python 3 and 2

Upvotes: 0

Sanju
Sanju

Reputation: 2194

def my_function_composition(f, g):
    return {key1: value2 for key1, value1 in f for key2, value2 in g if value1==key2}

Upvotes: 0

Related Questions