Jessica
Jessica

Reputation: 3173

dictionary returns none when there should be a value python

I have a small sample dataset:

import pandas as pd


df = {'ID': ['H576','H577','H578','H600', 'H700'],
  'CD': ['AAAAAAA', 'BBBBB', 'CCCCCC','DDDDDD', 'EEEEEEE']}

df = pd.DataFrame(df)

I read this in with pandas and transform these 2 columns into a dictionary with the 'ID' being the key and 'CD' being the value:

dictionary = df.set_index('ID')['CD'].to_dict()

because I need to do other things (which i will not go into details, it's a long story and my actual script is long script that involves many other things) , i need to save the dictionary as value-key pairs, reversed:

reversedic = dict()
for key, val in dictionary.items():
        reversedic.pop(val, key)    #python 2.7 uses dic.append() but for the python I have which is 3.5, 'dict' object has no attribute 'append', so is pop the correct code? 

later on in my larger script i will need to get the 'ID' when given a 'CD' value

z = reversedic.get('AAAAAAA')
print(z)

this should have returned H576 but it returned 'none' instead.

Upvotes: 1

Views: 621

Answers (4)

Merlin
Merlin

Reputation: 25659

Since create first Dict this way

dictionary = df.set_index('ID')['CD'].to_dict()

Why not?

reversedic = df.set_index('CD')['ID'].to_dict()

Then:

z = reversedic.get('AAAAAAA')
print(z)

or

z = reversedic['AAAAAAA']
print(z)

Upvotes: 1

gaganso
gaganso

Reputation: 3011

pop() returns the value for the key passed to it. The second parameter is default value which is returned if key is not present in the dictionary.

You can just do :

reversedic[key] = value

Upvotes: 2

Colonel Beauvel
Colonel Beauvel

Reputation: 31181

Why not directly:

reverseDict = {v:k for k,v in dictionary.iteritems()}

In [14]: reverseDict['AAAAAAA']
Out[14]: 'H576'

Upvotes: 3

Quinchilion
Quinchilion

Reputation: 922

From the docs about dict.pop():

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

If you want to add a key-value pair to the dictionary, use

reversedic[key] = val

Upvotes: 2

Related Questions