associative-array

In PHP, how do you change the key of an array element?

非 Y 不嫁゛ 提交于 2019-11-25 23:04:11
问题 I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value. I didn\'t see a function that does this, but I\'m assuming I need to provide the old key and new key (both of which I have) and transform the

Rename a dictionary key

痞子三分冷 提交于 2019-11-25 18:45:41
Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value? In case of OrderedDict, do the same, while keeping that key's position. For a regular dict, you can use: mydict[new_key] = mydict.pop(old_key) For an OrderedDict, I think you must build an entirely new one using a comprehension. >>> OrderedDict(zip('123', 'abc')) OrderedDict([('1', 'a'), ('2', 'b'), ('3', 'c')]) >>> oldkey, newkey = '2', 'potato' >>> OrderedDict((newkey if k == oldkey else k, v) for k, v in _.viewitems())