2014-10-09 61 views
-3

我必须合并两套:创建Python字典使用两套

colors={'GREEN','YELLOW','PURPLE','BLUE','RED'} 

children={'uri','ron','sigalit','ruti','alon'} 

到利用儿童作为键单字典。 我不允许使用循环,也不允许使用索引。 有关如何做到这一点的任何线索?

+1

@Cyber​​你使用Python 2.6或更早的版本? – 2014-10-09 13:34:21

+0

@AshwiniChaudhary 2.7。 3.x这个变化了吗? – CoryKramer 2014-10-09 13:34:44

+2

@Cyber​​是的,它也被移植到Python 2.7中。 – 2014-10-09 13:35:13

回答

2

你可以使用dict的理解。

children = {'uri','ron','sigalit','ruti','alon'} 
colors = {'GREEN','YELLOW','PURPLE','BLUE','RED'} 

>>> {x:y for x,y in zip(children,colors)} 
{'uri': 'GREEN', 'ruti': 'BLUE', 'ron': 'YELLOW', 'alon': 'RED', 'sigalit': 'PURPLE'} 
+0

他们必须保持集合 – 2014-10-09 13:35:50

+0

非常感谢你! – 2014-10-09 13:44:31

+0

@Chen Davidov'我不允许使用循环'。 Dict理解在内部使用循环。 – coldmind 2014-10-09 13:48:15

1
In [1]: colors={'GREEN','YELLOW','PURPLE','BLUE','RED'} 

In [2]: children={'uri','ron','sigalit','ruti','alon'} 

In [3]: dict(zip(children, colors)) 
Out[3]: 
{'alon': 'GREEN', 
'ron': 'RED', 
'ruti': 'PURPLE', 
'sigalit': 'BLUE', 
'uri': 'YELLOW'} 
+0

套的顺序不保留 – 2014-10-09 13:37:23

+0

@ChenDavidov套没有订单,所以我不认为这是可能的 – GP89 2014-10-09 13:38:39

+0

为什么你不能使用'list(colors)'和'list(children) '? Set是无序集合 – coldmind 2014-10-09 13:38:56