python - How would I pick out a sentence by only looking for one word from a text file - TagMerge
2How would I pick out a sentence by only looking for one word from a text fileHow 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

Asked 5 months ago
1
2 answers

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'

Source: link

-1

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

Source: link

Recent Questions on python

    Programming Languages