Development Tip

dict에 대한 키로서의 Python 변수

yourdevel 2020. 12. 8. 20:09
반응형

dict에 대한 키로서의 Python 변수


Python (2.7)에서이 작업을 더 쉽게 수행 할 수있는 방법이 있습니까? : 참고 : 모든 지역 변수를 사전에 넣는 것과 같은 멋진 작업은 아닙니다. 내가 목록에서 지정한 것들만.

apple = 1
banana = 'f'
carrot = 3
fruitdict = {}

# I want to set the key equal to variable name, and value equal to variable value
# is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?

for x in [apple, banana, carrot]:
    fruitdict[x] = x # (Won't work)

for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]

globals()함수는 모든 전역 변수를 포함하는 사전을 반환합니다.

>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}

라는 유사한 기능도 있습니다 locals().

이것이 정확히 당신이 원하는 것이 아니라는 것을 알고 있지만 파이썬이 변수에 대한 액세스를 제공하는 방법에 대한 통찰력을 제공 할 수 있습니다.

편집 : 단순히 사전을 사용하여 문제를 더 잘 해결할 수있는 것 같습니다.

fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3

한 줄짜리는 다음과 같습니다.

fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))

여기에 변수 나 값을 다시 입력 할 필요없이 한 줄에 있습니다.

fruitdict.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'fruitdict'})

mouad의 답변에 따라 접두사를 기반으로 변수를 선택하는 좀 더 비단뱀적인 방법이 있습니다.

# All the vars that I want to get start with fruit_
fruit_apple = 1
fruit_carrot = 'f'
rotten = 666

prefix = 'fruit_'
sourcedict = locals()
fruitdict = { v[len(prefix):] : sourcedict[v]
              for v in sourcedict
              if v.startswith(prefix) }
# fruitdict = {'carrot': 'f', 'apple': 1}

접두사와 sourcedict를 인수로 사용하여 함수에 넣을 수도 있습니다.


변수 자체의 위치를 ​​바인딩하려면 다음이 있습니다.

>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> fruitdict = {}
>>> fruitdict['apple'] = lambda : apple
>>> fruitdict['banana'] = lambda : banana
>>> fruitdict['carrot'] = lambda : carrot
>>> for k in fruitdict.keys():
...     print k, fruitdict[k]()
... 
carrot 3
apple 1
banana f
>>> apple = 7
>>> for k in fruitdict.keys():
...     print k, fruitdict[k]()
... 
carrot 3
apple 7
banana f

시험:

to_dict = lambda **k: k
apple = 1
banana = 'f'
carrot = 3
to_dict(apple=apple, banana=banana, carrot=carrot)
#{'apple': 1, 'banana': 'f', 'carrot': 3}

글쎄, 이것은 약간, 음 ... Pythonic이 아닌 ... 추악 ... 해 키쉬 ...

다음은 특정 체크 포인트를 가져온 후 생성 한 모든 지역 변수의 사전을 생성한다고 가정하는 코드 스 니펫입니다.

checkpoint = [ 'checkpoint' ] + locals().keys()[:]
## Various local assigments here ...
var_keys_since_checkpoint = set(locals().keys()) - set(checkpoint)
new_vars = dict()
for each in var_keys_since_checkpoint:
   new_vars[each] = locals()[each]

참고로 '체크 포인트'키를 캡처에 명시 적으로 추가합니다 locals().keys().이 경우에는 필요하지 않지만 [ '체크 포인트에 추가하기 위해 참조를 평면화해야하기 때문에 해당 슬라이스도 명시 적으로 가져옵니다. '] 목록. 그러나이 코드의 변형을 사용하고 변수를 추가함에 따라 값이 변경되는 ['checkpoint'] + portion (because that key was already inlocals () , for example) ... then, without the [:] slice you could end up with a reference to thelocals (). keys ()` 를 바로 가기로 설정하려고하면 .

Offhand I can't think of a way to call something like new_vars.update() with a list of keys to be added/updated. So thefor loop is most portable. I suppose a dictionary comprehension could be used in more recent versions of Python. However that woudl seem to be nothing more than a round of code golf.


why you don't do the opposite :

fruitdict = { 
      'apple':1,
      'banana':'f',
      'carrot':3,
}

locals().update(fruitdict)

Update :

don't use the code above check the comment.

by the way why you don't mark the vars that you want to get i don't know maybe like this:

# All the vars that i want to get are followed by _fruit
apple_fruit = 1
carrot_fruit = 'f'

for var in locals():
    if var.endswith('fruit'):
       you_dict.update({var:locals()[var])

This question has practically been answered, but I just wanted to say it was funny that you said

This isn't anything fancy, like putting all local variables into a dictionary.

Because it is actually "fancier"

what you want is:

apple = 1
banana = 'f'
carrot = 3
fruitdict = {}

# I want to set the key equal to variable name, and value equal to variable value
# is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?

names= 'apple banana carrot'.split() # I'm just being lazy for this post
items = globals()                    # or locals()

for name in names:
    fruitdict[name] = items[name]

Honestly, what you are doing is just copying items from one dictionary to another.

(Greg Hewgill practically gave the whole answer, I just made it complete)

...and like people suggested, you should probably be putting these in the dictionary in the first place, but I'll assume that for some reason you can't


a = "something"
randround = {}
randround['A'] = "%s" % a

Worked.

참고URL : https://stackoverflow.com/questions/3972872/python-variables-as-keys-to-dict

반응형