I'm learning Python. I know how to do this in JavaScript but I lack the syntax-knowledge at this very moment nor can I find examples that tell me how to do this.
I have the following Array of Objects:
john_williams_compositions = [
{"year": 1973, "Title": "The Poseidon Adventure", "type": "Best Orignal Score", "status": "nominated"},
{"year": 1974, "Title": "Cinderella Liberty", "type": "Best Original Score", "status": "nominated"},
{"year": 1974, "Title": "Tom Sawyer", "type": "Best Original Score", "status": "nominated"},
{"year": 1975, "Title": "Earthquake", "type": "Best Original Score", "status": "nominated"},
{"year": 1976, "Title": "Jaws", "type": "Best Original Score", "status": "Won"},
{"year": 1978, "Title": "Close Encounters of the Third Kind", "type": "Best Original Score", "status": "nominated"},
{"year": 1978, "Title": "Star Wars: Episode IV - A New Hope", "type": "Best Original Score", "status": "Won"},
{"year": 1979, "Title": "Superman", "type": "Best Original Score", "status": "nominated"},
{"year": 1981, "Title": "Star WArs: Episode V - The Empire Strikes Back", "type": "Best Original Score", "status": "nominated"},
{"year": 1983, "Title": "E.T. the Extra Terrestrial", "type": "Best Original Score", "status": "Won"},
{"year": 1983, "Title": "If We Were in Love", "type": "Best Original Song", "status": "nominated"},
{"year": 1985, "Title": "The River", "type": "Best Original Score", "status": "nominated"},
{"year": 1988, "Title": "Empire of the Sun", "type": "Best Original Score", "status": "nominated"}
]
Now I want to get all the objects with the status "Won"
in a new array.
I came up with this myself:
def won(list):
result = []
for x in list:
if x.status == "Won":
result.append[i]
return result
print(won(john_williams_compositions))
Can anyone jumpstart me with this?
x
is a dict
. Unlike Javascript (I gather), there is a syntactic difference between access the value for a given key in a dict
and accessing the value of an attribute.
x["foo"] # Value associated with key "foo"
x.foo # Value associated with the attribute "foo"
Your loop requires the former:
def won(list):
result = []
for x in list:
if x["status"] == "Won":
result.append[i]
return result