-1

Well I want to return an updated dictionary dependent on if else conditional statement through a function. But every time It returns null value instead of updated value. I wanted to update dictionary and return it on single line. Why the update function assign null value instead of updated values

def to_json(condition=True):
    ls = ["abc", "xyz", "123"]
    dis = {
        "id": 123,
        "value": "1122"
    }
    if condition is False:
        return dis
    else:
        return dis.update({"Key": ls})


print(to_json())

output: None

instead of: {'id': 123, 'value': '1122', 'Key': ['abc', 'xyz', '123']}

Dominique
  • 16,450
  • 15
  • 56
  • 112
  • This doesn't answer your question, but have some style tips: use `if not condition:` in place of `if condition is False:`, and use `dis["Key"] = ls` in place of `dis.update({"Key": ls})`. – Kevin Apr 09 '19 at 13:42

1 Answers1

2

The update() function returns nothing, so by returning the call to update the dict, you will always receive None

If you make the udpate to the dict before the return statement, then return the dict, you should see your results.

def to_json(condition=True):
    ls = ["abc", "xyz", "123"]
    dis = {
        "id": 123,
        "value": "1122"
    }
    if condition is False:
        return dis
    else:
        dis.update({"Key": ls})
        return dis


print(to_json())
Nordle
  • 2,915
  • 3
  • 16
  • 34
  • Thanks Matt B ! I have find the answer "The .update() method alters the dictionary in place and returns None. The dictionary itself is altered, no altered dictionary needs to be returned." – Adil Khurshid Apr 10 '19 at 07:19