Reputation: 3596
I did some research on how to use named array from PHP in python, while i found the following code example as they said can be done with dictionary.
shows = [
{"id": 1, "name": "Sesaeme Street"},
{"id": 2, "name": "Dora The Explorer"},
]
Source: Portion of code getting from here
Reference: Python references
But how could i adding a new value through a loop? While the references shown on how to adding single value by simply shows['key']="value" but i can't linking both of them. Can anyone please show me how to add the value into this dictionary through a loop?
For example:
for message in messages:
myvariable inside having two field
- Message
- Phone number
Update May i know how could i loop them out to display after aped list into dictionary? Thanks!
Upvotes: 2
Views: 19669
Reputation: 723
In short, you can do (list comprehension)
message_informations = [{"message": m.message, "phone": m.phone} for m in messages]
If you want to assing an id for each message_information and store in a dictionary (dict comprehension)
{_id: {"message": m.message, "phone": m.phone} for _id, m in enumerate(messages)}
Upvotes: 0
Reputation: 3774
You should be adding the dictionary into an array like :
friends = []
for message in messages:
dict = {"message" : message.message, "phone" : message.phone }
friends.append(dict)
to loop again, you can do it this way :
for friend in friends:
print "%s - %s" % (friend["message"], friend["phone"])
Upvotes: 4
Reputation: 30197
Effectively your example is a list of dictionaries, in PHP terms array of associative arrays.
To add an item you can do:
shows.append({ "id" : 3, "name" : "House M.D."})
[]
denotes a list
, or an array.
{}
denotes a dictionary
or an associative array.
Upvotes: 1