I need to do a data structure in python just like this:
array(
1 => array(url => "http://wwww.ff.com", msg => "msg 1..."),
2 => array(url => "http://wwww.yy.com", msg => "msg 2..."),
3 => array(url => "http://wwww.xx.com", msg => "msg 3..."),
);
I have search the documentation, but no clue. Can someone give me clue on how to do this?
Best Regards,
asked Mar 25, 2011 at 15:27
André
25.7k44 gold badges125 silver badges181 bronze badges
3 Answers 3
Simply use a list of dictionaries:
a = [{"url": "http://wwww.ff.com", "msg": "msg 1..."},
{"url": "http://wwww.yy.com", "msg": "msg 2..."},
{"url": "http://wwww.xx.com", "msg": "msg 3..."}]
print a[0]["url"]
# http://wwww.ff.com
Alternatively, you could use a list of tuples
a = [("http://wwww.ff.com", "msg 1..."),
("http://wwww.yy.com", "msg 2..."),
("http://wwww.xx.com", "msg 3...")]
print a[0][0]
# http://wwww.ff.com
or a list of named tuples:
from collections import namedtuple
UrlTuple = namedtuple("UrlTuple", "url msg")
a = [UrlTuple(url="http://wwww.ff.com", msg="msg 1..."),
UrlTuple(url="http://wwww.xx.com", msg="msg 2..."),
UrlTuple(url="http://wwww.yy.com", msg="msg 3...")]
print a[0].url
# http://wwww.ff.com
answered Mar 25, 2011 at 15:31
Sven Marnach
608k123 gold badges969 silver badges866 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Data types in Python can be freely nested:
multi = [[1, 2, 3], [4, 5, 6]]
If you need a more indepth solution, NumPy has a powerful selection of array handling tools.
answered Mar 25, 2011 at 15:32
mavnn
9,4994 gold badges36 silver badges53 bronze badges
Comments
You are looking for dictionaries:
[{"url":"http...", "msg":"msg 1..."}, {"url":"http...", "msg":"msg 12..."}, ...]
Comments
lang-py