Getting value of a list in Python

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

Answers


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))

Need Your Help

Controlling size / position of UINavigationItem titleView

iphone ios cocoa-touch uinavigationcontroller uinavigationbar

In my app, I have some custom titles (with lettering that isn't a font) stored in pngs that I want to put as the title of my navigation. I want the lettering in the titles all to be the same size for

ASP.NET MVC Session with ID in custom header

c# asp.net asp.net-mvc session-state

Is it possible in ASP.NET MVC (without writing toooo much code) to manually select what the current sessionId is? I don't mean like creating my own sessionId, but rather I want to store the session...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.