Programing

사전을 목록으로 변환 하시겠습니까?

lottogame 2020. 5. 21. 08:04
반응형

사전을 목록으로 변환 하시겠습니까? [복제]


가능한 중복 :
파이썬 사전을 튜플 목록으로 변환하는 방법은 무엇입니까?

계산을 수행하기 위해 Python 사전을 Python 목록으로 변환하려고합니다.

#My dictionary
dict = {}
dict['Capital']="London"
dict['Food']="Fish&Chips"
dict['2012']="Olympics"

#lists
temp = []
dictList = []

#My attempt:
for key, value in dict.iteritems():
    aKey = key
    aValue = value
    temp.append(aKey)
    temp.append(aValue)
    dictList.append(temp) 
    aKey = ""
    aValue = ""

그게 내 시도입니다 ...하지만 무엇이 잘못되었는지 알아낼 수 없습니까?


귀하의 문제는 당신이 가지고있다 key그리고 value그 문자열을 따옴표로, 당신에게있는 거 설정 즉, aKey문자열을 포함하도록 "key"아닌 변수의 값을 key. 또한 temp목록을 지우지 않으므로 두 개의 항목이 아닌 매번 목록에 추가합니다.

코드를 수정하려면 다음과 같이 시도하십시오.

for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

당신은 루프 변수에 복사 할 필요가 없습니다 key그리고 value내가 그들을 중퇴 있도록 사용하기 전에 다른 변수로합니다. 마찬가지로 추가를 사용하여 목록을 작성할 필요가 없으며 위와 같이 대괄호 사이에 목록을 지정할 수 있습니다. 그리고 우리는 가능한 한 짧기를 dictlist.append([key,value])원한다면 할 수있었습니다 .

또는 dict.items()제안 된대로 사용하십시오 .


dict.items()

트릭을 수행합니다.


파이썬에서는 dict 에서 list로 쉽게 변환 할 수 있습니다 . 세 가지 예 :

>> d = {'a': 'Arthur', 'b': 'Belling'}

>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]

>> d.keys()
['a', 'b']

>> d.values()
['Arthur', 'Belling']

을 사용해야합니다 dict.items().

다음은 문제에 대한 하나의 라이너 솔루션입니다.

[(k,v) for k,v in dict.items()]

결과 :

[('Food', 'Fish&Chips'), ('2012', 'Olympics'), ('Capital', 'London')]

아니면 할 수있다

l=[]
[l.extend([k,v]) for k,v in dict.items()]

에 대한:

['Food', 'Fish&Chips', '2012', 'Olympics', 'Capital', 'London']

 >>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
 >>> list(reduce(lambda x, y: x + y, a.items()))
 ['foo', 'bar', 'baz', 'quux', 'hello', 'world']

To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.


Probably you just want this:

dictList = dict.items()

Your approach has two problems. For one you use key and value in quotes, which are strings with the letters "key" and "value", not related to the variables of that names. Also you keep adding elements to the "temporary" list and never get rid of old elements that are already in it from previous iterations. Make sure you have a new and empty temp list in each iteration and use the key and value variables:

for key, value in dict.iteritems():
    temp = []
    aKey = key
    aValue = value
    temp.append(aKey)
    temp.append(aValue)
    dictList.append(temp)

Also note that this could be written shorter without the temporary variables (and in Python 3 with items() instead of iteritems()):

for key, value in dict.items():
    dictList.append([key, value])

If you're making a dictionary only to make a list of tuples, as creating dicts like you are may be a pain, you might look into using zip()

Its especialy useful if you've got one heading, and multiple rows. For instance if I assume that you want Olympics stats for countries:

headers = ['Capital', 'Food', 'Year']
countries = [
    ['London', 'Fish & Chips', '2012'],
    ['Beijing', 'Noodles', '2008'],
]

for olympics in countries:
    print zip(headers, olympics)

gives

[('Capital', 'London'), ('Food', 'Fish & Chips'), ('Year', '2012')]
[('Capital', 'Beijing'), ('Food', 'Noodles'), ('Year', '2008')]

Don't know if thats the end goal, and my be off topic, but it could be something to keep in mind.

참고URL : https://stackoverflow.com/questions/1679384/converting-dictionary-to-list

반응형