Sorry, I couldn't think of a better title for my question.
So I'm a starter at Python and I really trying to learn how to use it. My current problem deals with creating a simple way to reduce the results received from a python query.
If I understand what I'm dealing with, the LDAP query returns a List
of a List
of Dictionary
where value in the Dictionary
is a List
. That's a lotta stuff there to traverse through so I figured there has to be a nice magical python way to convert this to a List
of a Dictionary
where the value of the Dictionary
is just a simple string.
Currently, my code just simply to get the List
of Dictionary
but I still have the Dictionary
values as a List
themselves
for item in data:
results.append(item[1])
Once again, I'm a beginner so I don't really understand what to do from there. I'm also using Django if that's gonna help anyone understand my plight.
Edit (added data example):
The Structure is kinda like this:
data[index][1] = {'uid': ['restest'], 'mail': [''], 'givenName': ['Research'], 'cn': ['Research Test Account'], 'sn': ['Account']}
I'd like it to be instead of 'givenName': ['Research']
to be 'givenName': 'Reaseach'
Haha I'm not sure you ever want such a complicated data structure around. Consider refactoring your code to make your data structures easier to understand. Read: object-oriented programming, classes, functional programming principles.
Here's the answer if you just want to do it for a single dictionary:
data = {k:v[0] for (k,v) in data.items()}
Here it is in action:
>>> data = {'uid': ['restest'], 'mail': [''], 'givenName': ['Research'], 'cn': ['Research Test Account'], 'sn': ['Account']}
>>> data
{'mail': [''], 'sn': ['Account'], 'givenName': ['Research'], 'uid': ['restest'], 'cn': ['Research Test Account']}
>>> data = {k:v[0] for (k,v) in data.items()}
>>> data
{'mail': '', 'givenName': 'Research', 'cn': 'Research Test Account', 'sn': 'Account', 'uid': 'restest'}
All you're doing is re-mapping your dictionary to the first item of each list. If you want to iterate through all the levels of your structure and do this, just nest the above inside some list comprehensions:
[[[{k:v[0] for (k,v) in change_dict.items()} for change_dict in list_of_dicts]
for list_of_dicts in list_of_lists]
for list_of_lists in mydata]
It's not so bad to nest so many list comprehensions when you're only doing something to a "leaf" element in your data, but this is gonna get really messy if you try to manipulate your data structures at every level. See my comment at the beginning.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.