Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 update values in list based on dictionary
#1
Im quite new to python and struggling on this. Any help would be much appreciated please

I have a dictionary as follows:

teams -> {'42': 'arsenal', '48': 'chelsea', '43': 'Liverpool', '49': 'Man City', '24': 'Wolves'}

I have a a file of rows which one i split into a list looks like below:

['Hex', 'Team', 'League', 'Won League']
['0xDEFK', 'arsenal', 'EPL', 'Yes']
['0x1E56', 'chelsea', 'EPL', 'Yes']
['0xFDC0', 'liverpool', 'EPL', 'No']
['0x76YJ', 'Man City', 'EPL', 'Yes']
['0xAB7J', 'Wolves', 'EPL', 'No']



I want to be able to loop through above rows and update the second column "Team" with the number of that team from the "teams" dictionary

ie

EXAMPLE 1:
['0xDEFK', 'arsenal', 'EPL', 'Yes']

WOULD BECOME 42 because key for arsenal is 42:

['0xDEFK', '42', 'EPL', 'Yes']


EXAMPLE 2:
['0x1E56', 'chelsea', 'EPL', 'Yes']

WOULD BECOME 48 because key for chelsea is 48:

['0x1E56', '48', 'EPL', 'Yes']


I've something like below but not having much luck, what am i doing wrong? Is there a easier way to do this? Thanks in advance:

with open('info_output.txt', 'r') as info_outputfile:

    for line in info_outputfile:
        l = line.split('|') 
        #info = [Hex, Team, League, WonLeague]

        newlist = []
        for element in info:
            newlist.append ((element[0], dictionary [element[1]], element[4], element[3]))
            print newlist
The error i get when i run this script is:

Error:
Traceback (most recent call last): element[1] = dictionary[ element[1]] KeyError: '0'
Quote
#2
I suggest the following improvements
  1. The dictionary has the scores as keys and the teams as values, they want switching so the teams are the keys and the scores are the values.
  2. The first line from the text file you want to skip over it as its a header, to do this you can use next on info_outputfile
  3. 'liverpool' in the file is lower case l, 'Liverpool' in the dictionary has upper case L, one or the other must change so they match.
  4. There is one too many loops, remove the last one
  5. Change the line split variable from l to element
  6. The list indexes are wrong for the last two items from the split.
  7. The error shown does not match the code shown.
Quote
#3
Quote:I have a dictionary as follows:
teams = {'42': 'arsenal', '48': 'chelsea', '43': 'Liverpool', '49': 'Man City', '24': 'Wolves'}
I have a a file of rows which one i split into a list looks like below:

['Hex', 'Team', 'League', 'Won League']
['0xDEFK', 'arsenal', 'EPL', 'Yes']
['0x1E56', 'chelsea', 'EPL', 'Yes']
['0xFDC0', 'liverpool', 'EPL', 'No']
['0x76YJ', 'Man City', 'EPL', 'Yes']
['0xAB7J', 'Wolves', 'EPL', 'No']
I want to be able to loop through above rows and update the second column "Team" with the number of that team from the "teams" dictionary

So you iterate over the text file, line by line and split the fields.
You want to lookup the second field "Team" in the values of a dictionary.
This is the problem. Exchange the keys with values in your dictionary
and then the lookup is much easier:

>>> teams = {'42': 'arsenal', '48': 'chelsea', '43': 'Liverpool', '49': 'Man City', '24': 'Wolves'}
>>> teams
{'42': 'arsenal', '48': 'chelsea', '43': 'Liverpool', '49': 'Man City', '24': 'Wolves'}
>>> {v:k for k,v in teams.items()}
{'arsenal': '42', 'chelsea': '48', 'Liverpool': '43', 'Man City': '49', 'Wolves': '24'}
>>> teams = {v:k for k,v in teams.items()}
>>> teams
{'arsenal': '42', 'chelsea': '48', 'Liverpool': '43', 'Man City': '49', 'Wolves': '24'}
>>> teams['arsenal']
'42'
>>> teams[' arsenal ']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: ' arsenal '
>>> teams.get(' arsenal ', 'Team not found')
'Team not found'
>>> teams.get('arsenal', 'Team not found')
'42'
>>> 
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote
#4
Another possibility is to be creative with indexing without need to convert dictionary.

'Get index of needed value in list of dictionary values and find key with same index in list of dictionary keys':

>>> d = {1: 'ham', 2: 'eggs', 3: 'bacon'}
>>> value = 'eggs'
>>> [*d.keys()][[*d.values()].index(value)]    # instead of *d.keys() one may use *d
2
This way it is possible to have non-hashable values but still find corresponding key:

>>> d = {1: ['ham'], 2: ['eggs'], 3: ['bacon']}                             
>>> value = ['bacon']                                                       
>>> [*d.keys()][[*d.values()].index(value)]                         
3
NB! If there are several equal values this will return first one encountered.

Follow-up edit: so one can utilize this something like following:

>>> dct = {'1': 'one', '2': 'two', '3': 'three'}
>>> lst = [
...       ['one', 'uno'],
...       ['two', 'dos'],
...       ['three', 'tres']
... ]
>>> for row in lst:
...     row[0] = [*dct][[*dct.values()].index(row[0])]
...
>>> lst
[['1', 'uno'], ['2', 'dos'], ['3', 'tres']]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  How do I map a list of values to specified colors? larkypython 4 161 Nov-05-2019, 09:22 AM
Last Post: larkypython
  Exporting list with dictionary to Excel veromi22 0 118 Oct-15-2019, 12:54 AM
Last Post: veromi22
  Trying to color an excel row based on list curranjohn46 1 138 Oct-08-2019, 04:16 PM
Last Post: Aurthor_King_of_the_Brittons
  Create a dictionary from a list klllmmm 3 156 Oct-06-2019, 05:50 PM
Last Post: Gribouillis
  update dict as per range of values anna 7 296 Sep-13-2019, 04:37 PM
Last Post: anna
  pop default of two list of dictionary kk230689 1 107 Sep-10-2019, 12:12 PM
Last Post: ichabod801
  Python Script for parsing dictionary values from yaml file pawan6782 3 316 Sep-04-2019, 07:21 PM
Last Post: pawan6782
  Comaparing Float Values of Dictionary Against A Float Value & Pick Matching Key firebird 2 260 Jul-25-2019, 11:32 PM
Last Post: scidam
  Why does this list of lists end up with the same values alehak 2 280 Jul-18-2019, 12:34 PM
Last Post: perfringo
  How to create a list with all values being zero 357mag 4 257 Jul-14-2019, 03:43 PM
Last Post: ThomasL

Forum Jump:


Users browsing this thread: 1 Guest(s)