Clojure:将哈希映射键字符串转换为关键字吗? [英] Clojure: Convert hash-maps key strings to keywords?

查看:73
本文介绍了Clojure:将哈希映射键字符串转换为关键字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Aleph从Redis提取数据:

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"})

当我需要它时:


({{:name Tylenol,:how instructions})

({:name "Tylenol", :how "instructions})

我以前是通过以下方式创建新地图的:

I was previously creating a new map via:


{:name(m name),:how(m how)}

{ :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?

推荐答案

有一个方便的函数,称为关键字,它将字符串转换为适当的关键字:

There is a handy function called keyword that converts Strings into the appropriate keywords:

(keyword "foo")
=> :foo

因此,这只是使用此功能转换地图中所有键的情况。

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:

(into {} 
  (for [[k v] my-map] 
    [(keyword k) v]))

这篇关于Clojure:将哈希映射键字符串转换为关键字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆