sebelk
sebelk

Reputation: 644

Can python assign the same value to different keys at once?

Is possible to create a data sctructure like this?

w = {'London', 'Glasgow', 'Dublin' : 'rainy' , 'Paris', 'Berlin':  'cloudy', 'Tokyo', 'Montevideo' : 'sunny' }

(The above has invalid syntax, of course)

I'd want to avoid writing:

w = {'London' : 'rainy' , 'Glasgow' : 'rainy', 'Dublin' : 'rainy' , 'Paris' : 'cloudy' , 'Berlin':  'cloudy', 'Tokyo' : 'sunny' , 'Montevideo' : 'sunny' }

Is there a way to shorten it, and then access easily value for each value?

Upvotes: 2

Views: 274

Answers (2)

Ronald
Ronald

Reputation: 3315

You can group the values in tuples like this:

w = {('London', 'Glasgow', 'Dublin') : 'rainy' , ('Paris', 'Berlin'):  'cloudy', ('Tokyo', 'Montevideo') : 'sunny' }

Then you could write a small function that returns the value of the 'key' you are looking for. Because keys are now tuples, only a whole tuple can be used as a key. The following returns the value if your sub-key is part of the real key, or None when not found:

w = {('London', 'Glasgow', 'Dublin') : 'rainy' , ('Paris', 'Berlin'):  'cloudy', ('Tokyo', 'Montevideo') : 'sunny' }

def getme(searchkey, w):
    for key in w.keys():
        if searchkey in key:
            return w[key]
    return None

print(getme('London', w))
print(getme('Paris', w ))
print(getme('Moscow', w))

>>> rainy
>>> cloudy
>>> None

Upvotes: 1

shx2
shx2

Reputation: 64328

You can use dict.fromkeys multiple times and merge the results:

w = dict(
    **dict.fromkeys(['London', 'Glasgow', 'Dublin'], 'rainy'),
    **dict.fromkeys(['Paris', 'Berlin'], 'cloudy'),
)

There are many different ways to merge dicts. using multiple **-operators when creating the dict is just one of them.

Upvotes: 5

Related Questions