Multidimensional List/Dict/whatever?

I'd like to create a multidimensional array in Python to parse it later on. I'm a switcher from PHP so I'm a little bit confused of how to create a dict or list or anything else to get that data out this way. Anyone an idea?

for group, value in data:
    print '%s = %s' % (group, value)
    for member, value in group:
        print '   MEMBER: %s = %s' % (member, value)

>> 'Windows = 12%'
>> '   MEMBER: pc1 = 123'
>> '   MEMBER: pc2 = 321'
>> 'MacOS = 11%'
>> 'Linux = 13%'
>> '   MEMBER: pc3 = 213'
>> '   MEMBER: pc4 = 132'
>> ...

Answers


You can create a recursive list or dict to achieve it, I would prefer dict as you can name the variables e.g.

mydata = [
    {
        'name': 'Windows',
        'value': '12%',
        'members': [
            {
                'name': 'pc1',
                'value': 123,
                'members': []
            },
            {
                'name': 'pc2',
                'value': 321,
                'members': []
            },
        ]
    },
    {
        'name': 'Linux',
        'value': '11%',
        'members': [
            {
                'name': 'pc3',
                'value': 213,
                'members': []
            },
            {
                'name': 'pc4',
                'value': 132,
                'members': []
            },
        ]
    },
]

Now if you know your data structure is only 1 level deep, you can just iterate it like this

for topmember in mydata:
    print "%s = %s"%(topmember['name'], topmember['value'])
    for member in topmember['members']:
        print '   MEMBER: %s = %s' % (member['name'], member['value'])

output:

Windows = 12%
   MEMBER: pc1 = 123
   MEMBER: pc2 = 321
Linux = 11%
   MEMBER: pc3 = 213
   MEMBER: pc4 = 132

But if you don't know how much deep it is, e.g. members can further have more member which have more members and so on, you can recursively go thru it e.g.

def print_recursive(members, indent=''):
    for member in members:
        print "%s%s = %s"%(indent, member['name'], member['value'])
        print_recursive(member['members'], indent + '    ')

print_recursive(mydata)

output:

Windows = 12%
    pc1 = 123
    pc2 = 321
Linux = 11%
    pc3 = 213
    pc4 = 132

Need Your Help

XAMPP Not working with PHP includes?

php include xampp localhost

I've installed XAMPP on my laptop and followed so many different words of advise on this problem but none fix it.

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.