0

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

4
  • 2
    If 'UNP' where? In the whole outer dict? Commented Sep 30, 2012 at 20:55
  • 5
    It looks to me that you should be using a dict of dicts, not a dict of list of dicts. Commented Sep 30, 2012 at 20:57
  • Your question is difficult to understand. Do you mean you want to process the structure you have somehow? If you just want to use it, it doesn't matter where it came from, so it doesn't matter whether you created it with defaultdict or not. In any case you need to give an example of what you want to do, with code or at least pseudocode. Commented Sep 30, 2012 at 21:04
  • Why do you need a collections.defaultdict(list)? Do you want an empty list to be the default value for dictionary entries that are not set explicitly? Commented Sep 30, 2012 at 21:04

2 Answers 2

1

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
>>>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.