1

I have a list which contains 2 dictionaries as follows:

accuracy=[{'value':1,'key':'apple'}, {'value':2,'key':'orange'}]

I have a code like the below:

for fruit in accuracy:
    print fruit

The above code will give the following result:

{'value':1,'key':'apple'} {'value':2,'key':'orange'}

But i want something like this:

If i give name=fruit.key the output should be name=apple and same in the case for orange also and If i give name=fruit.value the output should be value=1 and similar case for other fruit too. how can I achieve this.I know the above code i.e; name=fruit.key wont produce my desired result.So is there anyway to get it?please help

1
  • 1
    Any reason your dict's aren't just {'apple': 1} and {'orange': 2} ? Commented Sep 21, 2012 at 11:31

1 Answer 1

5

You can do it like that:

accuracy=[{'value':1,'key':'apple'}, {'value':2,'key':'orange'}]
for fruit in accuracy:
    print 'name={key}'.format(**fruit)
    print 'value={value}'.format(**fruit)

I believe this meets your needs. You can read more on Python's string formatting (str.format() method) here:

Using dot notation

@mgilson mentioned another possibility, which may meet your requirements more. Although I believe this is an overkill in this case (why do it just to change notation?), it may be interesting to some, so I add it below:

# Here is the special class @mgilson mentioned:
class DotDict(dict):
    def __getattr__(self, attr):
        return self.get(attr, None)
    __setattr__=dict.__setitem__
    __delattr__=dict.__delitem__

accuracy=[{'value':1,'key':'apple'}, {'value':2,'key':'orange'}]    
for fruit in accuracy:
    # Convert dict to DotDict before passing to .format() method:
    print 'name={fruit.key}'.format(fruit=DotDict(fruit))
Sign up to request clarification or add additional context in comments.

2 Comments

You could even use print 'name = {fruit[key]}'.format(fruit=fruit) which is a bit closer to OP's request if I understand it correctly. (and if fruit were a DotDict ...)
@mgilson: Yes, or print 'name = {[key]}'.format(fruit). There are many possibilities to do that.

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.