Forum Archive

Trouble with dictionary

Dann239

I can find plenty of resources to create a dictionary with multiple keys per value, but I can't find how to set one up.
https://gist.github.com/PyDann/0440454db5a2218f30f2
I'm just passing a string to check of its existence in mydict. I thought I had it set up right but it fails.

Thanks for any help! ; )

Sebastian

Do you mean like this?

# -*- coding: utf-8 -*-
mydict = {('Sunny', 'Clear') : '☀️', 'Cloudy' : '☁️'}

for key, value in mydict.items():
    for k in key:
        mydict[k] = value

print mydict['Sunny']
print mydict['Clear']

print mydict['Cloudy']
Dann239

So my script takes the weather description out of the daily yahoo forecast and passes it to this function. Instead of writing 100 lines checking 'if description == ...". I figured a dictionary that I could just simple check the string against and return a value from.

ccc

I updated my comments in the gist... I believe that is a working solution.

henryiii

I've added a comment too; modifying the original dict makes lookup faster, and inheritance is a clean solution for the 'smart default dict' function that ccc wrote.

Note that

d['one'] = x
d['two'] = x

will only 'store' one copy of the value x, but if x is immutable, it will be hard to tell that it really is only one copy. (This is just they way Python works)