Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将列表为值的Python字典转换为简单字典_Python_Python 3.x_List_Dictionary - Fatal编程技术网

将列表为值的Python字典转换为简单字典

将列表为值的Python字典转换为简单字典,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,我有一本字典,它的值列表如下: dict = {"a":["b","c","d"]} 我想要这个表格: dict = {"a":"b","a":"c","a":"d"} 根据您的评论,您希望将dict内容写入csv文件。没有必要压平任何东西: d = {"a":["b","c","d"]} # never use dict or list as a variable name to not hide builtins with open("file.csv", "w", newline

我有一本字典,它的值列表如下:

dict = {"a":["b","c","d"]}
我想要这个表格:

dict = {"a":"b","a":"c","a":"d"}

根据您的评论,您希望将dict内容写入csv文件。没有必要压平任何东西:

d = {"a":["b","c","d"]}    # never use dict or list as a variable name to not hide builtins
with open("file.csv", "w", newline="") as fd:
    wr = csv.writer(fd)
    for k,v in d.items():
        for x in v:
            wr.writerow((k,x))

因为字典有唯一的键,所以不能创建目录。我认为元组列表是一个更好的主意。下面是一个如何实现的示例

dict = {"a":["b","c","d"]}

newList = list()

for key, value in dict.items():
    for i in value:
        newList.append((key, i))

print(newList)
输出如下所示

[('a', 'b'), ('a', 'c'), ('a', 'd')]

希望这能有所帮助。

dict
键是唯一的。也许您正在寻找
元组的
列表
,例如
[('a','b'),('a','c'),…]
?如果你能告诉我们更多,也许我们可以为你的用例提出一个更好的数据结构,你想用这个来完成什么?即使您可能有重复的密钥,当您使用
dict['a']
时,您希望返回什么?感谢您的回复。实际上,我正在尝试将dictionary dict={“a”:[“b”,“c”,“d”]}存储在一个CSV文件中,格式如下:a,ba,ca,d@azrara:这就是为什么你总是要给出问题的背景。不可能构建扁平字典(因为键是唯一的),但将内容写入CSV文件并不需要构建扁平字典。如果你编辑你的问题,说你想要的实际上是一个csv文件,你可以得到答案。@SergeBallesta好的,谢谢。我将在另一个问题中给出更多的上下文。使用理解比反复添加到列表中更具python风格(也更有效):
newlist=[(key,I)表示key,value in dict.items()表示I in value]
。对于Python初学者来说,可能不太可读,但实际上更像Python。