Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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_Pandas - Fatal编程技术网

Python 为字典中的每个键创建一个所有值的列表

Python 为字典中的每个键创建一个所有值的列表,python,pandas,Python,Pandas,我喜欢为每个县创建一个邮政编码列表,并将其分配给一个字典,该字典以键作为县的名称。例如,如果我有来自csv文件的邮政编码和县列,例如 邮政编码 县 92606 橙色 92607 橙色 90026 洛杉矶 90027 洛杉矶 90028 洛杉矶 使用groupby和。\u dict In [6]: df.groupby('County')['Zip code'].agg(list).to_dict() Out[6]: {'Los Angeles': [90026, 90027, 90028], '

我喜欢为每个县创建一个邮政编码列表,并将其分配给一个字典,该字典以键作为县的名称。例如,如果我有来自csv文件的邮政编码和县列,例如

邮政编码 县 92606 橙色 92607 橙色 90026 洛杉矶 90027 洛杉矶 90028 洛杉矶
使用
groupby
。\u dict

In [6]: df.groupby('County')['Zip code'].agg(list).to_dict()
Out[6]: {'Los Angeles': [90026, 90027, 90028], 'Orange': [92606, 92607]}

我会使用csv读卡器

import csv

file_name = "zip_codes.csv" #name of the csv file

with open(file_name, "r") as file: # opens the file (in read mode so nothing gets overwritten)
    reader = csv.DictReader(file)
    city_zip_dict = {} # make an empty dict to store the values
    for row in reader: #go through every row in the file
        county = row["County"]
        zip = row["Zip code"]
        if county not in city_zip_dict:
            city_zip_dict[county] = [zip] # Create a new list of zip codes for the county if there isn't one already
        else:
            city_zip_dict[county].append(zip) # if the county is already in the dictionary just add the new zip code to the list

成功了,非常感谢。对熊猫很陌生,所以很有帮助,再次谢谢你。对不起,我对熊猫很陌生,下次会小心的