I am using collections.defaultdict(list).
My print looks like the following:
{ 'A': [{'UNP': 'P01899'}],
'C': [{'PDB': '2VE6'}],
'B': [{'PDB': '2VE6'}, {'UNP': 'P01887'}],
'E': [{'PDB': '2VE6'}, {'UNP': 'P01887'}],
'D': [{'UNP': 'P01899'}],
'G': [{'UNP': 'P01899'}],
'F': [{'PDB': '2VE6'}],
'I': [{'PDB': '2VE6'}],
'H': [{'PDB': '2VE6'}, {'UNP': 'P01887'}],
'K': [{'PDB': '2VE6'}, {'UNP': 'P01887'}],
'J': [{'UNP': 'P01899'}],
'L': [{'PDB': '2VE6'}] }
What I want to do is use a clause if 'UNP' do something, if only 'PDB' and no 'UNP' then do something different.
I am very new to scripting. so any help is highly appreciated. thanks
Pedro Romano
11.2k4 gold badges48 silver badges50 bronze badges
2 Answers 2
one way is
>>> for key,val in my_dict.items():
... keys = [v.keys()[0] for v in val]
... if "UNP" in keys: print "UNP in",key
... elif "PDB" in keys: print "PDB in",key
...
UNP in A
PDB in C
UNP in B
UNP in E
UNP in D
UNP in G
PDB in F
PDB in I
UNP in H
UNP in K
UNP in J
PDB in L
>>>
answered Sep 30, 2012 at 21:24
Joran Beasley
114k13 gold badges168 silver badges187 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
If each item can have only up to 1 "UNP" and only up to 1 "PDB", you should use defaultdict(dict) in the beginning. Then you can do insertions like this:
mydict['A']['UNP'] = 'P01899'
And get automatically and easily a datastructure like
{ 'A': {'UNP': 'P01899'},
'C': {'PDB': '2VE6'},
'B': {'PDB': '2VE6', 'UNP': 'P01887'},
'E': {'PDB': '2VE6', 'UNP': 'P01887'},
'D': {'UNP': 'P01899'},
'G': {'UNP': 'P01899'},
'F': {'PDB': '2VE6'},
'I': {'PDB': '2VE6'},
'H': {'PDB': '2VE6', 'UNP': 'P01887'},
'K': {'PDB': '2VE6', 'UNP': 'P01887'},
'J': {'UNP': 'P01899'},
'L': {'PDB': '2VE6'} }
Then what you want is quite straightforward:
itemA = mydict['A']
if 'UNP' in itemA:
# now we have 'UNP'
elif 'PDB' in itemA:
# now we have PDB but not UNP
answered Sep 30, 2012 at 22:54
Antti Haapala
135k23 gold badges298 silver badges349 bronze badges
Comments
lang-py
'UNP'where? In the whole outer dict?defaultdictor not. In any case you need to give an example of what you want to do, with code or at least pseudocode.collections.defaultdict(list)? Do you want an empty list to be the default value for dictionary entries that are not set explicitly?