如何在 Julia 中反转字典? [英] How to reverse a dictionary in Julia?

查看:16
本文介绍了如何在 Julia 中反转字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一本字典,比如

If I have a dictionary such as

my_dict = Dict(
    "A" => "one",
    "B" => "two",
    "C" => "three"
  )

反转键/值映射的最佳方法是什么?

What's the best way to reverse the key/value mappings?

推荐答案

一种方法是使用推导式通过迭代键/值对来构建新字典,并在此过程中交换它们:

One way would be to use a comprehension to build the new dictionary by iterating over the key/value pairs, swapping them along the way:

julia> Dict(value => key for (key, value) in my_dict)
Dict{String,String} with 3 entries:
  "two"   => "B"
  "one"   => "A"
  "three" => "C"

在交换键和值时,您可能要记住,如果 my_dict 有重复的值(比如 "A"),那么新字典可能会少一些键.此外,在新字典中通过键 "A" 定位的值可能不是您期望的值(Julia 的字典不会以任何容易确定的顺序存储它们的内容).

When swapping keys and values, you may want to keep in mind that if my_dict has duplicate values (say "A"), then the new dictionary may have fewer keys. Also, the value located by key "A" in the new dictionary may not be the one you expect (Julia's dictionaries do not store their contents in any easily-determined order).

这篇关于如何在 Julia 中反转字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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