[英]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? Array(dict.values)
产生与上述相同的结果吗?
Is there an easier way to map the dictionary
based on keys
and not enumerate
them? 有没有更简单的方法可以根据
keys
映射dictionary
而不enumerate
keys
?
Asking because I'd like to use the same keys
to map different dictionaries
for their values. 问,因为我想使用相同的
keys
为它们的值映射different dictionaries
。
PS: It doesn't have to be sorted. PS:不必分类。
EDITED 已编辑
Consider the json below : 考虑下面的json:
{
"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. 我想绘制
forecast_numbers
& actual_numbers
values
对xaxis
的值。 Would like to know if there is an alternate way other than using enumerated()
for getting the values? 是否想知道除了使用
enumerated()
之外还有其他方法来获取值?
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]
. 假设你有一个在JSON数据
json
作为[String: AnyObject]
(Also assuming your json
never contains some broken data. Seemingly using too much !
.) (还假设您的
json
永远不会包含一些损坏的数据。似乎使用了太多!
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.