简体   繁体   中英

Swift - map dictionary based on keys

Consider the dictionary :

var dict : [String : String]! = ["12" : "This", "5" : "is", "52" : "a", "42" : "Test"]

var keys = Array(dict.keys)

var values : [String]! = [String]()
for (_, key) in keys.enumerated() {
    values.append(dict[key]!)
}

Will Array(dict.values) yield the same result as above?

Is there an easier way to map the dictionary based on keys and not enumerate them?

Asking because I'd like to use the same keys to map different dictionaries for their values.

PS: It doesn't have to be sorted.

EDITED

Consider the json below :

{
  "data": {
    "forecast_numbers": {
      "15": 6397822,
      "20": 985448,
      "76": 2499160,
      "130": 4480161
    },
    "actual_numbers": {
      "15": 6344454,
      "20": 1645125,
      "76": 1644789,
      "130": 2451170
    },
    "accuracy": {
      "15": -0.83415887469204,
      "20": 66.941837621062,
      "76": -34.18632660574,
      "130": -45.288350128489
    },
    "xaxis": {
      "15": "ABC",
      "20": "BCD",
      "76": "BNM",
      "130": "NNN"
    }
  }
}

I want to plot forecast_numbers & actual_numbers values against xaxis values. Would like to know if there is an alternate way other than using enumerated() for getting the values?

Your purpose is not clear enough with seeing your updated example, but if you just want to gather the values for the same key each, you can write something like this:

let data = json["data"] as! [String: [String: Any]]
let result = data["xaxis"]!.map {($0.key, $0.value, data["forecast_numbers"]![$0.key]!, data["actual_numbers"]![$0.key]!)}
print(result) //->[("130", NNN, 4480161, 2451170), ("20", BCD, 985448, 1645125), ("76", BNM, 2499160, 1644789), ("15", ABC, 6397822, 6344454)]

Assuming you have that JSON data in json as [String: AnyObject] .

(Also assuming your json never contains some broken data. Seemingly using too much ! .)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM