2016-08-11 2 views
0

{ '2234': '1', '233': '60'} 다음과 같은 사전을 작성하고 싶습니다. 생성되었습니다. 나는이 대답 한 페이지를 발견하고 나는 파이썬 2.7이 밖으로 시도하지만 여전히 내 코드를 실행하는 동안 나에게 오류를 제공합니다 : 오류로 나를 위해 내가 코드를 실행하면Python으로 CSV 파일에 사전 쓰기 2.7

with open('variabelen.csv', 'w') as csvfile: 
    writer = csv.writer(csvfile) 
    for name, items in a.items():  
     writer.writerow([name] + items) 

이가 보여줍니다 : 따라서 오류 -

Traceback (most recent call last): 
    File "/Users/Danny/Desktop/Inventaris.py", line 48, in <module> 
    Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging) 
    File "/Users/Danny/Desktop/Inventaris.py", line 9, in Toevoeging_methode_plus 
    writecolumbs() 
    File "/Users/Danny/Desktop/Inventaris.py", line 24, in writecolumbs 
    writer.writerow([name] + items) 
TypeError: can only concatenate list (not "str") to list 

답변

1

당신은 문자열 items로 목록 [name]을 연결합니다.

대신, 당신은 단순히 .writerows()를 통해 items()을 작성할 수 있습니다

233,60 
2234,1 

행의 순서는 비록 다를 수 있습니다

with open('variabelen.csv', 'w') as csvfile: 
    writer = csv.writer(csvfile) 
    writer.writerows(a.items()) 

, 그것은 다음과 같은 내용으로 variabelen.csv을 생산하는 것 a = {'2234': '1', '233': '60'}의 가치를 감안할 때 파이썬에서 원인 사전은 정렬되지 않은 컬렉션입니다.

+0

동일한 방법으로이 코드를 옮길 수 있습니까? 예를 들면; 233과 2234를 열 이름으로 사용하고 그 이름으로 값을 수집합니까? 고맙습니다! @alecxe – Pythoner1234