Kun Hwi Ko
Kun Hwi Ko

Reputation: 169

Better way to reorder list of dictionaries?

So I have a small data like this:

data = [
    {"Name":"Arab","Code":"Zl"},
    {"Name":"Korea","Code":"Bl"},
    {"Name":"China","Code":"Bz"}
]

I want to find a graph so that the x-axis is: "Bl", "Bz", "Zl" (alphabetic order)
and the y-axis is: "Korea", "China", "Arab" (corresponding to the codenames).

I thought of:

new_data = {}
for dic in data:
    country_data = dic["Name"]
    code_data = dic["Code"]
    new_data[code_data] = country_data

code_data = []
for codes in new_data.keys():
    code_data.append(codes)
code_data.sort()

name_data = []
for code in code_data:
    name_data.append(new_data[code])

Is there a better way to do this? Perhaps by not creating a new dictionary?

Upvotes: 3

Views: 67

Answers (3)

jpp
jpp

Reputation: 164623

Here's one way using operator.itemgetter and unpacking via zip:

from operator import itemgetter

_, data_sorted = zip(*sorted(enumerate(data), key=lambda x: x[1]['Code']))

codes, names = zip(*map(itemgetter('Code', 'Name'), data_sorted))

print(codes)
# ('Bl', 'Bz', 'Zl')

print(names)
# ('Korea', 'China', 'Arab')

Upvotes: 0

Tobi696
Tobi696

Reputation: 458

So here's the data:

data = [
    {"Name":"Arab","Code":"Zl"},
    {"Name":"Korea","Code":"Bl"},
    {"Name":"China","Code":"Bz"}
]

To create a new sorted list:

new_list = sorted(data, key=lambda k: k['Code'])

If you don't want to get a new list:

data[:] = sorted(data, key=lambda k: k['Code'])

The result is:

[{'Code': 'Bl', 'Name': 'Korea'}, {'Code': 'Bz', 'Name': 'China'}, {'Code': 'Zl', 'Name': 'Arab'}]

I hope I could help you!

Upvotes: 1

martineau
martineau

Reputation: 123423

Better way to produce same results:

from operator import itemgetter

data = [
    {"Name": "Arab",  "Code": "Zl"},
    {"Name": "Korea", "Code": "Bl"},
    {"Name": "China", "Code": "Bz"}
]

sorted_data = ((d["Code"], d["Name"]) for d in sorted(data, key=itemgetter("Code")))
code_data, name_data = (list(item) for item in zip(*sorted_data))

print(code_data)  # -> ['Bl', 'Bz', 'Zl']
print(name_data)  # -> ['Korea', 'China', 'Arab']

Upvotes: 0

Related Questions