2014-10-09 52 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