Brando__
Brando__

Reputation: 365

Python sorting deep in a datastructure

I'm in pretty far over my head right now for Python scripting and don't really understand what I'm doing.

I have a dictionary where the keys are strings and the values are lists of strings. I need to sort the strings within the list alphanumerically such that

"role_powerdns": [
  "name-2.example.com",
  "name-1.example.com",
  "name-3.example.com"

 ],

Looks like this

"role_powerdns": [
  "name-1.example.com",
  "name-2.example.com",
  "name-3.example.com"
 ],

The full original code I'm working off of is here for reference. https://github.com/AutomationWithAnsible/ansible-dynamic-inventory-chef/blob/master/chef_inventory.py

I don't fully understand myself how the code I'm working off of works, I just know the data structure it's returning.

My local additions to that base code is filtering out IPs and inserting .sub into the strings. I've tried reusing the comprehension syntax I've got below for modifying the strings to sort the strings. Could someone show provide an example of how to iterate through a nested structure like this? Alternatively if doing this sort of sorting so late in the script is not appropriate, when generally should it be handled?

    def filterIP(fullList):
       regexIP = re.compile(r'\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$')
       return filter(lambda i: not regexIP.search(i), fullList)

    groups = {key : [domain.replace('sub.example.com', 'example.com') for domain in filterIP(list(set(items)))] for (key, items) in groups.iteritems() }


    print(self.json_format_dict(groups, pretty=True))

Upvotes: 0

Views: 87

Answers (2)

Brando__
Brando__

Reputation: 365

fuglede's answer almost worked for me. What I needed to do instead was use iteritems. items was doing some funky local version that was being thrown away after the code block was done with it per this

Iterating over dictionaries using 'for' loops

 for key, value in groups.iteritems():
      value.sort()

Upvotes: 0

fuglede
fuglede

Reputation: 18201

If d is your dictionary, you can sort all its values by

for _, l in d.items():
    l.sort()

Upvotes: 1

Related Questions