developer tip

사전에 키, 값 쌍을 추가하는 방법은 무엇입니까?

copycodes 2020. 10. 31. 09:50
반응형

사전에 키, 값 쌍을 추가하는 방법은 무엇입니까?


이 질문에 이미 답변이 있습니다.

사전에 키, 값 쌍을 추가하는 방법?. 아래에서 다음 형식을 언급 했습니까?

{'1_somemessage': [[3L,
                    1L,
                    u'AAA',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 22, 30),
                    u'gffggf'],
                   [3L,
                    1L,
                    u'BBB',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 20, 30),
                    u'ffgffgfg'],
                   [3L,
                    1L,
                    u'CCC',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 22, 30),
                    u'hjhjhjhj'],
                   [3L,
                    1L,
                    u'DDD',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 21, 45),
                    u'jhhjjh']],
 '2_somemessage': [[4L,
                    1L,
                    u'AAA',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 22, 30),
                    u'gffggf'],
                   [4L,
                    1L,
                    u'BBB',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 20, 30),
                    u'ffgffgfg'],
                   [4L,
                    1L,
                    u'CCC',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 22, 30),
                    u'hjhjhjhj'],
                   [4L,
                    1L,
                    u'DDD',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 21, 45),
                    u'jhhjjh']]}

사전에 키, 값 쌍 추가

aDict = {}
aDict[key] = value

동적 덧셈이란 무엇을 의미합니까?


빠른 참조를 위해 다음 모든 메서드는 새 키 'a'가 아직없는 경우 추가하거나 제공된 새 값으로 기존 키 값 쌍을 업데이트합니다.

data['a']=1  

data.update({'a':1})

data.update(dict(a=1))

data.update(a=1)

예를 들어 키 'c'는 데이터에 있지만 'd'는없는 경우 다음 메서드는 'c'를 업데이트하고 'd'를 추가합니다.

data.update({'c':3,'d':4})  

"동적"이 무슨 뜻인지 잘 모르겠습니다. 런타임에 사전에 항목을 추가하는 것을 의미한다면 dictionary[key] = value.

If you wish to create a dictionary with key,value to start with (at compile time) then use (surprise!)

dictionary[key] = value

I got here looking for a way to add a key/value pair(s) as a group - in my case it was the output of a function call, so adding the pair using dictionary[key] = value would require me to know the name of the key(s).

In this case, you can use the update method: dictionary.update(function_that_returns_a_dict(*args, **kwargs)))

Beware, if dictionary already contains one of the keys, the original value will be overwritten.


If you want to add a new record in the form

newRecord = [4L, 1L, u'DDD', 1689544L, datetime.datetime(2010, 9, 21, 21, 45), u'jhhjjh']

to messageName where messageName in the form X_somemessage can, but does not have to be in your dictionary, then do it this way:

myDict.setdefault(messageName, []).append(newRecord)

This way it will be appended to an existing messageName or a new list will be created for a new messageName.


May be some time this also will be helpful

import collections
#Write you select statement here and other things to fetch the data.
 if rows:
            JArray = []
            for row in rows:

                JArray2 = collections.OrderedDict()
                JArray2["id"]= str(row['id'])
                JArray2["Name"]= row['catagoryname']
                JArray.append(JArray2)

            return json.dumps(JArray)

Example Output:

[
    {
        "id": 14
        "Name": "someName1"
    },
    {
        "id": 15
        "Name": "someName2"
    }
]

To insert/append to a dictionary

{"0": {"travelkey":"value", "travelkey2":"value"},"1":{"travelkey":"value","travelkey2":"value"}} 

travel_dict={} #initialize dicitionary 
travel_key=0 #initialize counter

if travel_key not in travel_dict: #for avoiding keyerror 0
    travel_dict[travel_key] = {}
travel_temp={val['key']:'no flexible'}  
travel_dict[travel_key].update(travel_temp) # Updates if val['key'] exists, else adds val['key']
travel_key=travel_key+1

참고URL : https://stackoverflow.com/questions/3776275/how-to-add-key-value-pair-to-dictionary

반응형