Home > Net >  finding values in dictionary based on their key
finding values in dictionary based on their key

Time:11-04

I'm trying to find the values of keys based on their 3 first letters. I have three different categories of subjects that i have to get the grade from, stored as value with the subject being key. I have ECO, GEO, and INF. As there are multiple subjects i want to get the values from every key containing either ECO, GEO or INF.

subject={"INFO100":"A"}
    
(subject.get("INF"))

In this method i don't get the value, i have to use the whole Key. Is there a work-a-round? I want the values seperately so i can calculate their GPA based on their field of study:)

CodePudding user response:

You need to iterate on the pairs, to filter on the key and keep the value

subject = {"INFO100": "A", "INF0200": "B", "ECO1": "C"}

grades_inf = [v for k, v in subject.items() if k.startswith("INF")]
print(grades_inf)  # ['A', 'B']

grades_eco = [v for k, v in subject.items() if k.startswith("ECO")]
print(grades_eco)  # ['C']

CodePudding user response:

For understanding porpoises, you can create a function that returns a dictionary, like:

def getGradesBySubject(dict, search_subject):
    return [grade for subject,grade in dict.iteritems() if subject.startwith(search_subject)]

CodePudding user response:

A said in the comments, the purpose of a dictionary is to have unique keys. Indexing is extremely fast as it uses hash tables. By searching for parts of the keys you need to loop and lose the benefit of hashing.

Why don't you store your data in a nested dictionary?

subject={'INF': {"INFO100":"A", "INFO200":"B"},
         'OTH': {"OTHER100":"C", "OTHER200":"D"},
         }

Then access:

# all subitems
subject['INF']

# given item
subject['INF']['INFO100']

CodePudding user response:

I'd suggest using a master dict object that contains a mapping of the three-letter subjects like ECO, GEO, to all subject values. For example:

subject = {"INFO100": "A",
           "INFO200": "B",
           "GEO100": "D",
           "ECO101": "B",
           "GEO003": "C",
           "INFO101": "C"}

master_dict = {}
for k, v in subject.items():
    master_dict.setdefault(k[:3], []).append(v)

print(master_dict)
# now you can access it like: master_dict['INF']

Output:

{'INF': ['A', 'B', 'C'], 'GEO': ['D', 'C'], 'ECO': ['B']}

If you want to eliminate duplicate grades for a subject, or just as an alternate approach, I'd also suggest a defaultdict:

from collections import defaultdict

subject = {"INFO100": "A",
           "INFO300": "A",
           "INFO200": "B",
           "GEO100": "D",
           "ECO101": "B",
           "GEO003": "C",
           "GEO102": "D",
           "INFO101": "C"}

master_dict = defaultdict(set)
for k, v in subject.items():
    master_dict[k[:3]].add(v)

print(master_dict)
defaultdict(<class 'set'>, {'INF': {'B', 'A', 'C'}, 'GEO': {'D', 'C'}, 'ECO': {'B'}})
  • Related