Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
put a key in dictionary into another key and remove it from dictionary:

Idiots way:
data = {
'username': 'alireza@gmail.com'
}
data['email'] = data['username']
del data['username']

Tech C**P way:
data = {
'username': 'alireza@gmail.com'
}
data['email'] = data.pop('username')

pop access the data and remove it from data payload. In case username is not in data, an error will be raised. To prevent such an error give it default value:
data['email'] = data.pop('username', 'NO_USERNAME')

#pop #python #dictionary #code_improvement
If you are using python 3.5 or greater and want to merge to dictionaries:
>>> a = {'a': 1}
>>> b = {'b': 2}
>>> {**a, **b}
{'a': 1, 'b': 2}

That's it! You have merged 2 dictionaries in the most simplest way ever. :)

If you are using python 2.7 or python 3.4 or less, merge dictionaries as below:
def merge_two_dicts(a, b):
c = a.copy()
c.update(b)
return c

python #python3 #merge #dictionary
Data Analysis


Create a dataframe from dictionary in Pandas:

import pandas
data = [{'id': 1, 'name': 'alireza'}, {'id': 2, 'name': 'Mohsen'}]
# Creating a dataframe from a dictionary object
df = pandas.DataFrame(data)

Now if you print dataframe:
> df
id name
0 1 alireza
1 2 Mohsen

NOTE: the first column is the index column.


In order to turn it to a dictionary after your aggregation, analysis, etc just use to_dict like below:

df.to_dict(orient='records')
[{'id': 1, 'name': 'alireza'}, {'id': 2, 'name': 'Mohsen'}]

You are right! We didn't do anything useful on records, but the goal is to tell you how to turn dataframe to a dictionary not more.

NOTE: on older version of pandas you have to use outtype='records' rather than orient='records'.

#python #pandas #to_dict #outtype #orient #dictionary #dataframe
Sometimes in coding we see a python code like below:

users.get('extra_info').get('browser')


The above code is error prone. get method is usually used to prevent throwing error when accessing a non-existent key. For instance if we try to access extra_info that does not exist, the code below will throw KeyError exception:

> users['extra_info']

Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'extra_info'


In case users variable does not contain extra_info, None will be returned and the get will be applied on None value, to prevent such error you need to return {} as default value:

users.get('extra_info', {}).get('browser')

That curly braces will do the job in case extra_info field is not present in users variable.


#python #dictionary #get #keyError
How to turn a dictionary into a string?

extra_data = {'iso': 'IR', 'address': 'Iran - Tehran - Azadi'}
' - '.join('{}:{}'.format(key, val) for key, val in extra_data.items())

The output would be:

iso:IR - address:Iran - Tehran - Azadi

NOTE: it could come in handy in case you want to store a variable dictionary structure into NO-SQL database.

#python #dictionary #string