根据原始字典中的N个键创建N个新词典

时间:2015-11-06 19:53:55

标签: python loops dictionary

我是python和这里的新手。我需要根据原始字典中的N个键创建N个新词典。 假设我有OriginalDict {a:1, b:2, c:3, d:4, e:5, f:6}我需要创建6个新词典,其中键(新键相同)是原始值。这样的事情:

Dict1 {Name:a,...}, Dict2 {Name:b,...}, Dict3 {Name:c,...}.....
Dict6 {Name:f...}

这是我的代码:

d = {}     
for key in OriginalDict:
    d['Name'] = key

我有一本新词典,但仅限于最后一把钥匙。

print d 

{Name:f} 

如果键是相同的话,我猜cos'字典中的最后一个值会覆盖前一个值

请告知...... :)

5 个答案:

答案 0 :(得分:2)

例如,如果我们将所有这些词组放在列表中,我们就可以使用这种理解

dicts = [{'Name': k} for k in OriginalDict]

让我们试一试

>>> OriginalDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
>>> dicts = [{'Name': k} for k in OriginalDict]
>>> dicts
[{'Name': 'd'}, {'Name': 'c'}, {'Name': 'a'}, {'Name': 'b'}, {'Name': 'e'}, {'Name': 'f'}]

声明6 new dictionaries having as keys (new keys are same) the value of the original似乎与你的例子相矛盾,至少对我而言。

在这种情况下我们可以做到

dicts = [{v: k} for k, v in OriginalDict.items()]

让我们试一试:

>>> dicts = [{v: k} for k, v in OriginalDict.items()]
>>> dicts
[{4: 'd'}, {3: 'c'}, {1: 'a'}, {2: 'b'}, {5: 'e'}, {6: 'f'}]

答案 1 :(得分:0)

在python 3.x中:

for key in OriginalDict.keys():
     d = {}
     d ['Name'] = key

这将为原始的每个键提供一个新的词典。现在,您可以将它们保存在列表中或另一个字典中,如:

 New_Dicts = []
 for key in OriginalDict.keys():
     d = {}
     d ['Name'] = key
     New_Dicts.append(d)

或者,

 New_Dicts = {}
 for i,key in enumerate(OriginalDict.keys()):
     d = {}
     d ['Name'] = key
     New_Dicts[i] = d

答案 2 :(得分:0)

我认为你想要创建一个函数,它是一个生成器,然后调用该函数传入字典然后产生你的新函数:

orig = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}

def make_sub_dictionaries(big_dictionary):
    for key, val in big_dictionary.iteritems():
        yield {'name': key, 'val': val }

# if you want them one by one, call next 

first = make_sub_dictionaries(orig).next()

print first

# if you want all of them 
for d in make_sub_dictionaries(orig):
    print str(d)
    # do whatever stuff you need to do

答案 3 :(得分:0)

一种方法如下:

OriginalDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
newDicts = [{'Name':v} for k,v in enumerate(OriginalDict.values())]

会给你

>>> newDicts
[{'Name': 1}, {'Name': 3}, {'Name': 2}, {'Name': 5}, {'Name': 4}, {'Name': 6}]

答案 4 :(得分:0)

首先,这不会保持秩序。您需要使用OriginalDict来保存订单。

my_dict={'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
j=0
for key, value in my_dict.iteritems():
    j +=1
    exec("Dict%s = %s" % (j,{key:value}))

现在输入时。

>>> print Dict1
    {'a':1}
>>> print Dict2
    {'c':3}