Home > Blockchain >  How would I pick out a sentence by only looking for one word from a text file
How would I pick out a sentence by only looking for one word from a text file

Time:04-14

The contents of the text file I'm reading into looks like

{'race': {'asian': 1.5386780205517425e-05,
          'indian': 1.2399948445818154e-05,
          'black': 2.54539722632785e-08,
          'white': 99.71753358840942,
          'middle eastern': 0.11004179250448942,
          'latino hispanic': 0.1723980880342424},
 'dominant_race': 'white', 'region': {'x': 183, 'y': 167, 'w': 286, 'h': 286}}

I want to be able to take the dominant race and store it in a variable. But do not know how to take it out and store it in a variable. also note as when the program runs the dominant race will change.

CodePudding user response:

Your data is a dictionary. Dictionaries have key and value attributes. For example:

my_dict = {'Indian': 2, 'Asian':4}

In which "Indian" and "Asian" are the keys and 2 and 4 are the values for those keys.

In your question, your data has three keys: race', 'dominant_race and region. All you need to do to see the keys is the following command:

my_dict.keys()

Which will print:

dict_keys(['race', 'dominant_race', 'region'])

So, to get dominant_race you need to run the following:

my_dict['dominant_race']

which in your example will give you:

'white'

CodePudding user response:

Assuming you have got the data from the text file into a dict data:


This will store the the dominant race in dom_race and the value of that race in dom_val:

# max() for highest value
# data['race'].items() gets a (key, value) tuple from the dict (data)
# key=lambda x: x[1] tells max() to look at the value, rather than the key

dom_val, dom_race = max(data['race'].items(), key=lambda x: x[1])
>>> dom_val
99.71753358840942
>>> dom_race
'white'

Edit: I did not notice the 'dominant_race' key lol, you can just use this:

dom_race = data['dominant_race']
dom_val = data['race'][dom_race]

Let me know is this is not how you want it stored

  • Related