将随机值设置为字典的一半并复制其余部分

Setting random values to half of the dictionary and copying the rest

我有一个由其他列表创建的 python 字典:

a = dict.fromkeys(some_list)

因为我通过上面的命令创建了这个字典,所以我在字典中的所有值都是 None 正如预期的那样。它看起来像这样:

a = {('A', 'B'): None,
     ('A', 'C'): None,
     ('B', 'A'): None,
     ('C', 'A'): None}

我想要的是:能够通过 random.uniform(0,1).

None 值更改为随机数

但是我不想对整个字典执行此操作,而只是前 2 个键(('A', 'B')('A', 'C'))和其余键(('B', 'A')('C', 'A')) 应该从前 2 个键复制。

以下将所有值设置为随机数。但是我找不到一种方法来将前两个设置为随机的,其余的在不对密钥进行硬编码的情况下进行复制。

for key in a:
    a[key] = random.uniform(0, 1)

有什么建议吗?

假设您的 dict 中的键没有按任何特定顺序插入:

for key in a:
    n = random.uniform(0, 1)
    a[key] = n
    if (key[1], key[0]) in a:
        a[key[1], key[0]] = n
visited = set()

for key in a:

  if key in visited:
    continue
  
  # mark key as visited
  visited.add(key)
  visited.add(key[::-1])

  value = np.random.uniform(0, 1)

  a[key] = value
  a[key[::-1]] = value

更动态和有效的解决方案是散列给定的键,这样元组顺序被忽略

def hash_tuple(t):

  hash_value = 0

  for elem in t:
    
    if isinstance(elem, int):
      
      hash_value += elem
    
    elif isinstance(elem, str):

      hash_value += ord(elem)
    
    else:

      raise ValueError(f'Invalid Type {type(elem)}')
  
  return hash_value

global_seed = np.random.randint(0, 100)

for key in a:

  seed = hash_tuple(key) + global_seed
  random = np.random.RandomState(seed)

  value = random.uniform(0, 1)

  a[key] = value

我的方法不仅允许键元组中的两个元素,可以是任意数字,顺序也不重要。

import random

a = {('A', 'B'): None,
     ('A', 'C'): None,
     ('B', 'A'): None,
     ('C', 'A'): None}

tuple_group_dict = {t: ''.join(sorted(t)) for t in a.keys()}
# print(tuple_group_dict)
group_rand_dict = {g: random.uniform(0, 1) for g in tuple_group_dict.values()}
# print(group_rand_dict)
for k in a:
    a[k] = group_rand_dict[tuple_group_dict[k]]
print(a)

# {('A', 'B'): 0.19127468345979626, ('A', 'C'): 0.5162477118368421, ('B', 'A'): 0.19127468345979626, ('C', 'A'): 0.5162477118368421}