markdown python_dict

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown python_dict相关的知识,希望对你有一定的参考价值。

# Dictionary

#### Find value by key
```python
value = d.get(key)
```

##### Check if value exisit
```python
# Nomral dict
if d.get(key):
  d[key] = 0
  
# Nested dict:
if not d[key]:
  d[key] = 0
```

#### Loop each key/value pair
```python
# This work in python3
# For python two just loop through d
for k,v in d.items()
     # do something
```

#### Nested Dictionary (wrapper function)
```python
from collections import defaultdict
nested_dict = lambda: defaultdict(nested_dict)
d = nested_dict()
```

#### Find key by value
- cannot be done directly
- better to check if the value exist first, to prevent keyerror
- value as list -> find the index of the query value -> check the content in the key list
```python
# check if a value exist
value in d.values()
# find key
key = list(d.keys())[list(d.values()).index(value)]
```

#### To dataframe/ Series
```python
# To dataframe, d is the dictionary (python3)
df = pd.DataFrame(list(d.items()),columns=["a","b"])
# In python2 can just give pd.DataFrame a dict items (d.items() return list in python3), but in python3 d.items is a iter item (need to be iterated)
df = pd.DataFrame(d.items(),columns=['a','b'])


# Or to series
s = pd.Series(d)
# series wih it own index
s = pd.Series(d,name="ValueName") 
s.index.name = "KeyName"
s = s.reset_index()  # Free the key out by using new autocrement index
s.to_csv("s.csv")

# This doesn't work becuase DataFrame method accept scalar value only, list/dictionary will not work
pd.DataFrame(d)
```

以上是关于markdown python_dict的主要内容,如果未能解决你的问题,请参考以下文章

人生苦短_我用Python_dict(字典)_003

Markdown温故知新:Markdown面面观

markdown转换为图片

转换rst到markdown总结

markdown [Markdown HowTo]作为Markdown语法的秘籍

python markdown干啥用的