相关疑难解决方法(0)

在python中反转字典

可能重复:
Python反向/反向映射
交换Python中字典中唯一值的键

您好我想了解如何反转和比较字典值:例如:

如果我有一个带键的字典:这样的值格式

     dicta =  [1:2, 9:8, 4:6, 3:2, 0:7, 1:34, 9:90, 1:8, 67:43, 54:23]
Run Code Online (Sandbox Code Playgroud)

我如何反转它,使上面的dicta的值成为键,键成为这样的值:

     dictb =  [2:1, 8:9, 6:4, 2:3, 7:0, 34:1, 90:9, 8:1, 43:67, 23:54]  
Run Code Online (Sandbox Code Playgroud)

我正在使用python 2.5 pls帮助

python

1
推荐指数
1
解决办法
1万
查看次数

反转Swift字典中值的键,收集重复值

我有以下字典:

let dict = ["key1": "v1", "key2": "v1", "key3": "v2"]
Run Code Online (Sandbox Code Playgroud)

我想交换键的值,以便结果是:

result = ["v1": ["key1", "key2"], "v2": ["key3"]]
Run Code Online (Sandbox Code Playgroud)

在不使用for循环的情况下如何做到这一点(即更优雅)?

dictionary swift

1
推荐指数
2
解决办法
613
查看次数

如何反转字典中键的值分配?解决算法

groups_per_user 函数接收一个字典,其中包含带有用户列表的组名。就像 Linux 系统中的组。用户可以属于多个组。填空以返回一个以用户为键、以用户组列表为值的字典。

基本上我试图将组分配给用户而不是用户分配给组

这就是我迄今为止尝试过的:

def groups_per_user(group_dictionary):
    user_groups = {}
    groups = []
    # Go through group_dictionary
    for group,users in group_dictionary.items():
        # Now go through the users in the group
        for user in users:
        # Now add the group to the list of
          # groups for this user, creating the entry
          # in the dictionary if necessary
          groups.append(group)
          user_groups[user] = group

    return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }))
Run Code Online (Sandbox Code Playgroud)

如何遍历抛出列表,同时尽可能高效地将用户添加到组名中?

请原谅我的语法,这是我的第一个问题。谢谢

python algorithm

1
推荐指数
1
解决办法
2万
查看次数

如何用值列表展平字典?

我正在尝试“压平”一本看起来像这样的字典:

d = {
    "USA": ["US", "United States"],
    "SGP": ["JP", "Japan", "Singapore"]
}
Run Code Online (Sandbox Code Playgroud)

我想要的格式是这样的:

new_d = {
    "United States": "USA",
    "US": "USA",
    "JP": "SGP",
    "Japan": "SGP",
    "Singapore": "SGP"
}
Run Code Online (Sandbox Code Playgroud)

python dictionary python-3.x python-3.7

1
推荐指数
1
解决办法
1230
查看次数

标签 统计

python ×3

dictionary ×2

algorithm ×1

python-3.7 ×1

python-3.x ×1

swift ×1