使用键集创建字典

时间:2017-04-29 23:00:23

标签: python dictionary

我有2首字典:

a = {'a':5, 'b':3, 'c':1}
b = {"ca":10, "sd":4, "aa":2}

我想要获得的是:

z = {'a':"ca", 'b':"sd", 'c':"aa"}

我该怎么做?

编辑:

我希望将a的第一个键与b的第一个键匹配,将第二个键与b的第二个键匹配,依此类推。

3 个答案:

答案 0 :(得分:0)

试试这个:

fs.readFile('list.txt', function(err, data){
        if(err) throw err;
        var lines = data.split('\n');
        var rand = [Math.floor(Math.random()*lines.length)];
        var rlist = lines[rand]
})

答案 1 :(得分:0)

在(现在编辑成含糊不清的)评论中,您建议您考虑的顺序是"频率"。将其解释为按字典值排序的含义,您可以通过压缩按相应值排序的键来创建新的字典:

In [14]: dict(zip(sorted(a, key=a.get), sorted(b, key=b.get)))
Out[14]: {'a': 'ca', 'b': 'sd', 'c': 'aa'}

这是有效的,因为a.get是一个为我们提供值的方法,因此当我们对a进行排序(其中迭代在键上)时,我们通过增加值来对它们进行排序。

In [15]: sorted(a, key=a.get)
Out[15]: ['c', 'b', 'a']

但是,这并没有说明在关系的情况下该做什么。为了解决这个问题,您可以将参数排序为sorted(例如sorted(sorted(a),key=a.get)))或使用关键函数(例如sorted(a, key=lambda x: (a[x], x))),以便至少输出是确定性的。

答案 2 :(得分:0)

在这种情况下,您需要使用OrderedDict来保留订单。这是一个例子:

import collections
import itertools

a = collections.OrderedDict()
b = collections.OrderedDict()

# add the data based on the order that you need
a['a'] = 5
a['b'] = 3
a['c'] = 1

b["ca"] = 10
b["sd"] = 4
b["aa"] = 2

# put them together. I user izip and iterkeys assuming you have a large data set
# also assuming the order in the new dictionary doesn't matter otherwise you have to use OrderedDict again.
z = {i: j for i, j in itertools.izip(a.iterkeys(), b.iterkeys())}

print z
>> {'a': 'ca', 'c': 'aa', 'b': 'sd'}
相关问题