Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort dictionary by value?

My dictionary like this:

var items = [Int: [String]]() 
var itemsResult = [Int: [String]]()

itmesResult stores the data downloaded from server. and pass the data to items use of items = itmesResult

the value has 3 elements like ["Apple","/image/apple.png","29"] and I want to sort the dictionary by first value which is Apple.

for (k,v) in (itemsResult.sorted(by: { $0.value[0] < $1.value[0] })) { 
  items[k] = v
}

The result of above code is not my expectation.

I would like to sort it alphabetically how can I do this?

Edit:

origin:

1:["Apple","/image/apple.png","29"]
2:["AAA","/image/aaa.png","29"]
3:["Banana","/image/banana.png","29"]

sorted:

2:["AAA","/image/aaa.png","29"]
1:["Apple","/image/apple.png","29"]
3:["Banana","/image/banana.png","29"]

I would like to sort it by first value.

like image 435
yz_ Avatar asked Jan 17 '26 21:01

yz_


2 Answers

So if I take your example, this does the trick:

var items = [Int: [String]]()

items[0] = ["Apple","/image/apple.png","29"]
items[1] = ["AAA","/image/aaa.png","29"]
items[2] = ["Banana","/image/banana.png","29"]

let itemResult = items.sorted { (first: (key: Int, value: [String]), second: (key: Int, value: [String])) -> Bool in
    return first.value.first! < second.value.first!
}

print (itemResult)

The right thing to do is to use objects of course, and note that I'm not null checking the "first" object in each array, but this is not a problem to change.

Let me know if this is what you were looking for, the output is:

[(1, ["AAA", "/image/aaa.png", "29"]), (0, ["Apple", "/image/apple.png", "29"]), (2, ["Banana", "/image/banana.png", "29"])]

EDIT: Also note, that this case doesn't actually "sort" the dictionary, because a dictionary is by definition not sorted, this creates an array of key-value objects sorted using the array indexes

like image 64
unkgd Avatar answered Jan 19 '26 10:01

unkgd


Instead of saving these variable into an array of arrays, make them an array of dictionaries.

You can do this like so:

var dictionaries:[Dictionary<String, String>] = []
for item in items {
  let dictionary = {"name": item[0], "url": item[1], "id" : item[2]}
  dictionaries.append(dictionary)
}

You can get your sorted list of dictionaries like this:

dictionaries.sorted(by: { $0["name"] < $1["name"] })
like image 25
Daniel Avatar answered Jan 19 '26 11:01

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!