-1

I have a dictionary, this is a example dict it can have any number of fields

{'name': 'satendra', 'occupation': 'engineer', 'age': 27}

How can i convert this to tuple so that it will result ordered list of tuple.

# Expected output
[('name', 'satendra'), ('occupation', 'engineer'), ('age', 27)]

UPDATE

OrderedDict are useful when ordered list of tuple passed to it not for a JSON object, so i guess this is not a duplicate

Satendra
  • 6,755
  • 4
  • 26
  • 46
  • by order do you mean preserve the key, value pairs? – sam-pyt Nov 26 '17 at 14:44
  • if `name` key is first field in my dict so it should also come first when i convert it to tuple – Satendra Nov 26 '17 at 14:46
  • 1
    Use `OrderedDict`, which *is* essentially a list of tuples. – DeepSpace Nov 26 '17 at 14:46
  • i tried OrderedDict but when i pass my dict to it, output is unordered – Satendra Nov 26 '17 at 14:48
  • 1
    @Satendra Of course. You need to use `OrderedDict` to begin with. – DeepSpace Nov 26 '17 at 14:49
  • @DeepSpace i m getting json response from third party how can i use it to make ordered dict. – Satendra Nov 26 '17 at 14:50
  • 1
    JSON objects are also unordered. The keys simply _don't have an order_; there is nothing to preserve. "[An _object_ is an unordered set of name/value pairs.](http://json.org/)". – ChrisGPT was on strike Nov 26 '17 at 14:52
  • @Chris yes thats why i asked if there is any possible way to do it. if not i don't think the question will get down votes. – Satendra Nov 26 '17 at 14:53
  • Again, _**there is no order to preserve**_. The third party providing the response can send JSON responses with object keys in any order at all. This order can vary from request to request. There simply is no difference between `{"foo": 1, "bar": 2}` and `{"bar": 2, "foo": 1}`. – ChrisGPT was on strike Nov 26 '17 at 14:55

3 Answers3

3

Like you already understood from the comments, there is no order to preserve since there is no order to begin with. This JSON may arrive from the server in any arbitrary order.

However, if you know the keys you are interested in you can construct the list of tuples yourself.

Note that this code iterates over a separate tuple of keys in a known order. You will have to maintain that tuple manually.

relevant_keys = ('name', 'occupation', 'age')
data = {'occupation': 'engineer', 'age': 27, 'name': 'satendra'}
list_of_tuples = [(key, data[key]) for key in relevant_keys]
print(list_of_tuples)
#  [('name', 'satendra'), ('occupation', 'engineer'), ('age', 27)]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Thanks @DeepSpace I got that fact that json object is unordered and there is no meaning to preserving its order, i was just curious if it can be done. – Satendra Nov 26 '17 at 15:08
  • @Satendra : Yes it can be done, as I commented below my answer, but you have to be lucky to get the JSON packed in desired order. If the server delivering it is so polite to do it for you, you can parse it and keep the original order. Otherwise, there is no point in trying it. The thing is, server has no reason to send you an ordered JSON. :D – Dalen Nov 26 '17 at 16:09
1

Use OrderedDict() as suggested in comments, but correctly:

from collections import OrderedDict

d = OrderedDict([('name', 'satendra'), ('occupation', 'engineer'), ('age', 27)])

You define it as you would like your output to be. Then you use it as you would normal dictionary.

And when you want your list of tuples back, you do:

t = d.items()

You can use this solution when you know what keys to expect and you cannot use OrderedDict():

def sortdict (d, keys=["name", "occupation"]):
    mx = len(keys)
    def customsortkey (key):
        try: return keys.index(key)
        except: return mx
    kys = sorted(d, key=customsortkey)
    return [(key, d[key]) for key in kys]

This function will sort everything in the input dictionary "d" according to the order set by "keys" list. Any item in the dictionary, without its key present in list "keys" will be put to the end of the output in arbitrary order. You can indicate keys that aren't present in the dictionary, The output will be a list of tuples (key, value) as you require.

This is one of possible solutions and it is far from ideal. I.e. we can start a discussion about its efficiency and overhead. But really, in practice it will work just fine, and will handle any unexpected keys nicely. More efficient version of this function would be to use a dictionary to denote the order of keys instead of the list. A dictionary having the key in question for a key and an sorting index for its value. Like this:

def sortdict (d, keys={"name": 0, "occupation": 1}):
    mx = len(keys)
    kys = sorted(d, key=lambda k: keys.get(k, mx))
    return [(key, d[key]) for key in kys]
Dalen
  • 4,128
  • 1
  • 17
  • 35
  • Read the comments. OP has no control over the creation of the dictionary as it is a response from an API. – DeepSpace Nov 26 '17 at 15:04
  • Comments arrived while I was typing the answer. I'll suggest a solution but you already outlined it. There is nothing else possible if not knowing the present keys, except writing your own JSON parser and hoping that server will send the JSON constructed in required order. Which isn't likely. – Dalen Nov 26 '17 at 15:13
  • Here you go @DeepSpace, I think you will like my edit. – Dalen Nov 26 '17 at 16:14
-4

MyDict = {'name': 'satendra', 'occupation': 'engineer', 'age': 27}

MyList = []

For key in MyDict:

MyList.append( (key,MyDict[key]) )

Now MyList is a list of tuples.