Clojure:将哈希映射键字符串转换为关键字?
我使用 Aleph 从 Redis 中提取数据:
(apply hash-map @(@r [:hgetall (key-medication id)]))
问题是这些数据返回时带有键字符串,例如:
({"name" "Tylenol", "how" "instructions"})
当我需要它时:
({:name "Tylenol", :how "说明})
我之前通过以下方式创建了一个新地图:
{ :name (m "名字"), :how (m "如何")}
但这对于大量的键来说效率很低。
如果有一个函数可以做到这一点?或者我必须循环遍历每个?
I'm pulling data from Redis using Aleph:
(apply hash-map @(@r [:hgetall (key-medication id)]))
The problem is this data comes back with strings for keys, for ex:
({"name" "Tylenol", "how" "instructions"})
When I need it to be:
({:name "Tylenol", :how "instructions})
I was previously creating a new map via:
{ :name (m "name"), :how (m "how")}
But this is inefficient for a large amount of keys.
If there a function that does this? Or do I have to loop through each?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您还可以使用
clojure.walk
库通过函数keywordize-keys
来实现所需的结果,这也会递归地遍历映射,因此它将“关键字化”中的键也有嵌套映射
http://clojuredocs.org/clojure_core/clojure.walk/keywordize-keys
You can also use the
clojure.walk
library to achieve the desired result with the functionkeywordize-keys
This will walk the map recursively as well so it will "keywordize" keys in nested map too
http://clojuredocs.org/clojure_core/clojure.walk/keywordize-keys
有一个名为 keyword 的方便函数,可以将字符串转换为适当的关键字:
所以它只是一个使用此函数转换地图中所有键的情况。
我可能会使用具有解构的列表理解来执行此操作,例如:
There is a handy function called keyword that converts Strings into the appropriate keywords:
So it's just a case of transforming all the keys in your map using this function.
I'd probably use a list comprehension with destructuring to do this, something like:
我同意 djhworld,
clojure.walk/keywordize-keys
就是你想要的。值得一看 clojure.walk/keywordize-keys 的源代码:
逆变换有时对于 java 互操作很方便:
I agree with djhworld,
clojure.walk/keywordize-keys
is what you want.It's worth peeking at the source code of
clojure.walk/keywordize-keys
:The inverse transform is sometimes handy for java interop:
也许值得注意的是,如果传入的数据是
json
并且您使用的是clojure.data.json
,则可以指定key-fn
code> 和一个value-fn
用于操作解析字符串的结果(docs< /a>) -Perhaps it is worth noting that, if the incoming data is
json
and you are usingclojure.data.json
, you can specify both akey-fn
and avalue-fn
for manipulating results on parsing the string (docs) -您可以使用 zipmap 非常优雅地实现此目的:
基本上,zipmap 允许通过分别指定键和值来创建映射。
You can achieve this very elegantly using
zipmap
:Basically,
zipmap
allows to create a map by specifying keys and values separately.使用
keyword
函数和reduce-kv
。如果我有地图,例如
我可以做
Using the
keyword
function andreduce-kv
.If I have a map e.g.
I can do
我赞同 @mikera 的
基于
的答案。或者,不是最简洁的,而是使用 assoc+dissoc/reduce 的另一个选项是:I second @mikera's
into
based answer. Alternatively, not the most concise but, another option using assoc+dissoc/reduce would be: