简体   繁体   English

迭代第一个列表[]中的每个值到另一个列表[]上以形成字典{}

[英]Iterate each value in the first list [] over another list [] to form dictionary {}

Two list as below 两个清单如下

Suits = ["Hearts", "Diamonds", "Clubs", "Spades"] 西服 = [“心脏”,“钻石”,“俱乐部”,“黑桃”]

values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] = ['A','2','3','4','5','6','7','8','9','10','J','Q' , 'K']

I would like to create a dictionary as below 我想创建一个字典如下

Cards = {"Hearts" : "A", "Hearts": "2", "Hearts" : "3"......} = {“心”:“ A”,“心”:“ 2”,“心”:“ 3” ......}

Each one of the items in suits should iterate with all the items in the values list. 西装中的每个物品都应与列表中的所有物品一起进行迭代。 I tried with {}.Fromkeys() but i was not successful. 我尝试使用{} .Fromkeys(),但未成功。

Please help. 请帮忙。 Thanks 谢谢

You are trying to create a dictionary with the same key appearing multiple times, which is not allowed. 您正在尝试创建一个字典,该字典具有多次出现的相同键,这是不允许的。

Instead you could have something like: 相反,您可能会遇到以下情况:

Cards = {"Hearts" : ['A','2',...,'K'], "Diamonds": ['A','2',...,'K'],......} 卡= {“心”:['A','2',...,'K'],“钻石”:['A','2',...,'K'],... ...}

And the code for this would be: 并且此代码为:

suits = ["Hearts", "Diamonds", "Clubs", "Spades"] 
values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
cards = {}

for suit in suits:
    cards[suit] = values

Going through with your wish would result in a dictionary in which one key has multiple values. 如您所愿,将生成一本字典,其中一个键具有多个值。

If you want a table with all possible combinations of your lists, where you can filter for either 'Suits' or 'values' you could write it into a pandas.DataFrame: 如果您想要一个包含列表所有可能组合的表格,可以在其中筛选“ Suits”或“ values”,则可以将其写入pandas.DataFrame:

Suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
both = [(onesuit,onevalue) for onesuit in Suits for onevalue in values]

import pandas as pd
pd.DataFrame(both, columns=['Suits', 'values'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM